Example Scenario :-
I am using HTML and JS in frontend . For backend I am using Express . For Authentication I am using JWT .
Basic thing I know is that JWT is generally set in Authorization header when it is sent back to server .
What I want :-
Let us assume client requested post /user/login route giving their credentials through form . Auth middleware will verify the credentials and generate a jwt token using some payload .
My problem starts here , how to set this jwt on the client side and get it back in the header while navigating user to an authenticated page where I want user to redirect when they successfully login .
Something like below :-
app.post('/user/login' , authMiddleware , async (req , res) => {
res.redirect('/user/createTask')
}
Assume /user/createTask is expecting jwt which it will verify before letting user to enter into the route .
So what has to be in the authMiddleware so that jwt is set in the client side in local Storage or somewhere and get it back in the Authorization header .
If there are things to be done on client side to make it work , Please suggest that too . How this whole scenario will work ?
If you're sending the credentials through a form, then you won't be able to capture the response when you send a redirection response. The redirect will be handled by the browser, and your JS will not have access to anything that you send in the response.
For this scenario to work, you would have to call the post /user/login
endpoint through javascript. Then you can receive the response from your server. Read any tokens from it (which can be e.g. in the body of the response), set the tokens somewhere in store and then call the /user/createTask
endpoint. If you want to use JWTs sent in an Authorization
header, you will have to call all your endpoints through javascript. The browser can't add an Authorization
header to the request. You can store the token in a cookie (the response from login can set the cookie), then the browser will send the cookie together with the request.