user6277772
user6277772

Reputation:

Implementation of JWT correctly

I'm developing website with django rest framework, django rest framework jwt for backend and next.js, react, redux for frontend.

With the assumption,

'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=300),
'JWT_ALLOW_REFRESH': True,
'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),
'JWT_AUTH_COOKIE': 'token'

Based on above, I have a few questions.

  1. When and How to refresh token

access token will expired 5 minutes. Within 5 minutes, user can request the page which has permission_classes = (IsAuthenticated,) with access token. If 5 minutes have passed, cookies(access token) will disappear automatically and user need to login again. To avoid this, there is the system of refresh token, right? If it's right, When and How to refresh token is correct? Before requesting to backend with access token, always compare the expiration of access token to current time, then if it will expire soon, stop requesting once, switch to refresh token with axios first, after getting new token, restart requesting with new token... Is it correct way?

  1. access token will disappear if it has expired

Because it's cookies, right? For example, After user login and left from computer for 10 minutes. User came back and try to see website, but he needs to login again. Because there is no more access token in cookies and also cannot refresh token as well. What should I do?

I want user not to make trying login many times and keep user logged in until refresh token will expired.

Upvotes: 0

Views: 431

Answers (1)

felixmosh
felixmosh

Reputation: 35493

You can use the "interceptor" concept, for example, axios has it, you can add a response interceptor, and if the server returns a special error ("token_expired"), then that interceptor will access the refresh-token api with the refresh-token that it has, get a fresh access-token and retry the last failing request.

Checkout the first answer in here: https://github.com/axios/axios/issues/934#issuecomment-322003342

Hope this is clear.

Upvotes: 1

Related Questions