I am developing a web project with microservices. In the backend, I have a Login service which is responsible for checking the user credentials and returning a valid JWT. I have another service called Views which is responsible for serving the UI and sending requests to other services. Every request coming from the client first visits Views service and then the requests are delivered to proper services.
The code for sending ajax request to "/login" route in the Views service:
function login(){
$('#login-form').submit(function(){
$.ajax({
url: $('#login-form').attr('action'),
type: 'POST',
data : $('#login-form').serialize(),
success: function(res, status, xhr){
window.localStorage.setItem("x-access-token", xhr.getResponseHeader("x-access-token"));
$.ajax({
url: "/user/profile",
type: "GET",
headers: {
"x-access-token": window.localStorage.getItem("x-access-token")
},
success: function () {
window.location.replace("/user/profile")
},
error: function (response) {
alert("Error in GET: " + response)
}
});
}, error: function (response) {
alert(response)
}
})
});
}
Code that delivers the request to Login service:
@views_blueprint.route("/login", methods=["POST"])
def user_login():
email = request.form["email"]
password = request.form["password"]
r = requests.post("http://login:5000/login", json={"data": {"email": email, "password": password}})
try:
login_resp = r.json()
if login_resp["status"] == 201:
@after_this_request
def send_token(response):
response.headers["x-access-token"] = login_resp["token"]
return response
return json.dumps(login_resp)
else:
return render_template("/error/error.html", error_code=login_resp["status"], error_message=login_resp["message"])
except Exception as e:
return render_template("/error/error.html", error_code=500, error_message=f"Error occurred. {e}")
I can successfully send login request and get token back and store it in the localStorage. Issue I am having is, after logging in I need to redirect the user to a protected route and I need to add the JWT to the request headers. I tried to achieve this with an ajax GET request in the function login(). However, the GET request is never sent instead Flask renders the JSON object returned in the user_login() function.
How can I overcome this issue? If what I am doing is the wrong way, could anyone point me in the right direction?
I have just deal with JWT myself, so I saw you and I just wanted to give you a tip, I hope it will help you.
Your problem, if I've read that correctly, is that after a successful login you want to forward the user and valid token to the actual page in your app that is marked with jwt_required?
I always do it like this:
Nice day