What is the flow of using JWT work on the frontend?

Viewed 1048

I am new to web dev. I built a backend using Django Rest Framework and am using JWT to handle auth.

Now, I want to connect my backend to my frontend in React. But, I am confused how this should be done. Here are my question:

What is the whole flow of requesting and using JWT access and refresh tokens? Like, when should I request a new access token with my refresh token and when should I request a new refresh token? Thanks!

3 Answers

I will make a quick response:

  1. Flow of requesting and using JWT:

A picture worth a thousand words.

enter image description here

  1. The access token is not lasting forever. Whenever it expires, you have to request a new access token with your refresh token.

enter image description here

  1. Refresh tokens can expire, although their expiration time is usually much longer than access tokens. To handle this case, almost all implementations I've seen return a known error code of 'invalid_grant' that you can check for on the client-side and handle by your business. (ex: Show login page...)

Regarding your questions:

  1. What is the whole flow of requesting and using JWT access and refresh tokens?
  • I don't know you're using what's package about JWT, having too many packages about Django JWT on github (pyjwt, djangorestframework_simplejwt, ...). And Im using pyjwt in my application, because I want to custom my authentication in-app for security.
  • The workflow:
    • When FE send request to login/signup APIs, BE generate a token by using JWT, and return that token in the response.
    • FE store that token on local storage, using it for sending other requests.
    • BE will take the token by each request from FE to verify. The same as TokenAuthentication of DRF, we must be custom it when using pyjwt. Will verify the JWT token instead.
  1. when should I request a new access token with my refresh token and when should I request a new refresh token?
  • You can request a new access token after that token is expired.
  • When you're using djangorestframework_simplejwt you can see the refresh token but in my case (pyjwt), I just need re-generate jwt token again :)

There could be options, but simple flow is next:

  1. You do auth and get access and refresh tokens from a backend and save them as cookies.
  2. You use your access token until you get error 401 because access token has expired
  3. Then you try to refresh your tokens using your refresh token. If you use axios on frontend, good option to write a middleware for this case. This middleware will refresh tokens and repeat a last request. There should be recipes in google.
  4. If success you got new pair of access and refresh tokens and continue your workflow.
  5. If fail, you need to auth again to get tokens.
Related