Home > database >  How to send JWT to front end server after successful login for storage on localStorage?
How to send JWT to front end server after successful login for storage on localStorage?

Time:12-04

In my current application after the users logs in with google (passport strategy), I generate a JWT token on the server and then I have no idea how to send it back whilst also redirecting the user to the front end website.

While searching I read that the front end should fetch the token but does that mean I have to cache the JWT until it is requested and set some cookie with the key to get the token in cache? I tried doing that but that felt like I was reinventing the wheel and opening my self to some security vulnerability.

CodePudding user response:

You can send the JWT token in header or as a payload, and at the frontend you just need to attach the JWT token with every request when sending it to the server. The server should have the logic to validate before passing the request to next middleware if the token is valid the request will be passed to next middleware else unauthorised will be return.

You can send the token in headers, payload, query whatever you like, but widely people attach token in header under Authentication.

I recommend you checking this link, it has step by step process to send and validate JWT token with Node and Express.

You can also check this for node and react.

CodePudding user response:

Unfortunately, the accepted answer does not seem to answer the question. It is a good answer for sending from the frontend (e.g. web application) to a backend (API or similar).

But I understand that you want to send the token from the backend to the frontend. In this case, there are several way to transmit that token. They are widely used by OAuth2 Framework protocol.

Using a callback Uri

This is one of the most used technic. The backend sever generates a redirect response (status code 303) with the token in the query string. As an example

HTTP/1.1 303 See Other
Location: http://frontend.org/?token=xxxxxxxxxxx

You can also use a fragment property

HTTP/1.1 303 See Other
Location: http://frontend.org/#token=xxxxxxxxxxx

Code Exchange

Another method very similar is to generate a unique and one-time-use code that will be exchanged for the token using an additional request.

HTTP/1.1 303 See Other
Location: http://frontend.org/?code=xxxxxxxxxxx

On the fronted side, get the code and ask the token to the backend (using fetch)

POST /give/me/the/token HTTP/1.1
Host: backend.com
Content-Type: application/json

{
  "code": "xxxxxxx"
}
  • Related