Django REST JWT Refresh

Karesh A picture Karesh A · Mar 2, 2017 · Viewed 12.5k times · Source

Implemented Django REST and authentication using JWT. For JWT token we have to refresh it before it expire. After expired JWT wont give new token.

For my mobile device I need to refresh the token every 10 mins (JWT_EXPIRATION_DELTA). and if user is not active for more than 10 minutes, then I need to ask to login. Is there any way that I can refresh the token even after JWT token expired. (we can limit the time to refresh as 2 day)

Whats the best way to handle this behavior in Mobile.

Thanks.

Answer

np8 picture np8 · Nov 26, 2017

Refreshing tokens in django-rest-framework-jwt

The django-rest-framework-jwt (v. 1.11.0) does not support "Refresh Tokens" as described for example here. It only supports refreshing non-expired tokens; It makes easy to implement a sliding expiration window with width of JWT_EXPIRATION_DELTA. For example, with settings

'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=300),
'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),

user cannot be inactive for more than five minutes in order to stay logged in (docs).

Real Refresh Tokens, please?

It is possible to implement the "Refresh Tokens", which are very long lived ("never expiring") tokens, stored in a database, just like in conventional "HTTP Sessions & SessionIDs". This is actually already been implemented for the django-rest-framework-jwt in django-rest-framework-jwt-refresh-token. Another possibility is to use django-rest-framework-simplejwt which also implements the JWT with Access and Refresh Tokens (full example at Medium).

But.. why?

Compared to using only Access Token JWT's, using Refresh Tokens makes possible to revoke access after the Access Token is expired. Refesh Tokens make it possible to have very long ("lifetime of a mobile device") lasting tokens. One may ask why shouldn't you just stick with sessions (sessionid in a Cookie, and session data in database table), if you are creating collection of Refresh Tokens in a database, and accessing that. Using an Access token with expiration time of one hour will mean that database must be accessed once per hour (instead once per PUT/POST request when using "traditional" sessions). In addition, you gain all the usual benefits of JWT tokens (ease of use in microservice network, for example).