[security] JWT (JSON Web Token) automatic prolongation of expiration

I would like to implement JWT-based authentication to our new REST API. But since the expiration is set in the token, is it possible to automatically prolong it? I don't want users to need to sign in after every X minutes if they were actively using the application in that period. That would be a huge UX fail.

But prolonging the expiration creates a new token (and the old one is still valid until it expires). And generating a new token after each request sounds silly to me. Sounds like a security issue when more than one token is valid at the same time. Of course I could invalidate the old used one using a blacklist but I would need to store the tokens. And one of the benefits of JWT is no storage.

I found how Auth0 solved it. They use not only JWT token but also a refresh token: https://auth0.com/docs/tokens/refresh-tokens

But again, to implement this (without Auth0) I'd need to store refresh tokens and maintain their expiration. What is the real benefit then? Why not have only one token (not JWT) and keep the expiration on the server?

Are there other options? Is using JWT not suited for this scenario?

This question is related to security authentication jwt

The answer is


In the case where you handle the auth yourself (i.e don't use a provider like Auth0), the following may work:

  1. Issue JWT token with relatively short expiry, say 15min.
  2. Application checks token expiry date before any transaction requiring a token (token contains expiry date). If token has expired, then it first asks API to 'refresh' the token (this is done transparently to the UX).
  3. API gets token refresh request, but first checks user database to see if a 'reauth' flag has been set against that user profile (token can contain user id). If the flag is present, then the token refresh is denied, otherwise a new token is issued.
  4. Repeat.

The 'reauth' flag in the database backend would be set when, for example, the user has reset their password. The flag gets removed when the user logs in next time.

In addition, let's say you have a policy whereby a user must login at least once every 72hrs. In that case, your API token refresh logic would also check the user's last login date from the user database and deny/allow the token refresh on that basis.


I was tinkering around when moving our applications to HTML5 with RESTful apis in the backend. The solution that I came up with was:

  1. Client is issued with a token with a session time of 30 mins (or whatever the usual server side session time) upon successful login.
  2. A client-side timer is created to call a service to renew the token before its expiring time. The new token will replace the existing in future calls.

As you can see, this reduces the frequent refresh token requests. If user closes the browser/app before the renew token call is triggered, the previous token will expire in time and user will have to re-login.

A more complicated strategy can be implemented to cater for user inactivity (e.g. neglected an opened browser tab). In that case, the renew token call should include the expected expiring time which should not exceed the defined session time. The application will have to keep track of the last user interaction accordingly.

I don't like the idea of setting long expiration hence this approach may not work well with native applications requiring less frequent authentication.


How about this approach:

  • For every client request, the server compares the expirationTime of the token with (currentTime - lastAccessTime)
  • If expirationTime < (currentTime - lastAccessedTime), it changes the last lastAccessedTime to currentTime.
  • In case of inactivity on the browser for a time duration exceeding expirationTime or in case the browser window was closed and the expirationTime > (currentTime - lastAccessedTime), and then the server can expire the token and ask the user to login again.

We don't require additional end point for refreshing the token in this case. Would appreciate any feedack.


Good question- and there is wealth of information in the question itself.

The article Refresh Tokens: When to Use Them and How They Interact with JWTs gives a good idea for this scenario. Some points are:-

  • Refresh tokens carry the information necessary to get a new access token.
  • Refresh tokens can also expire but are rather long-lived.
  • Refresh tokens are usually subject to strict storage requirements to ensure they are not leaked.
  • They can also be blacklisted by the authorization server.

Also take a look at auth0/angular-jwt angularjs

For Web API. read Enable OAuth Refresh Tokens in AngularJS App using ASP .NET Web API 2, and Owin


I solved this problem by adding a variable in the token data:

softexp - I set this to 5 mins (300 seconds)

I set expiresIn option to my desired time before the user will be forced to login again. Mine is set to 30 minutes. This must be greater than the value of softexp.

When my client side app sends request to the server API (where token is required, eg. customer list page), the server checks whether the token submitted is still valid or not based on its original expiration (expiresIn) value. If it's not valid, server will respond with a status particular for this error, eg. INVALID_TOKEN.

If the token is still valid based on expiredIn value, but it already exceeded the softexp value, the server will respond with a separate status for this error, eg. EXPIRED_TOKEN:

(Math.floor(Date.now() / 1000) > decoded.softexp)

On the client side, if it received EXPIRED_TOKEN response, it should renew the token automatically by sending a renewal request to the server. This is transparent to the user and automatically being taken care of the client app.

The renewal method in the server must check if the token is still valid:

jwt.verify(token, secret, (err, decoded) => {})

The server will refuse to renew tokens if it failed the above method.


jwt-autorefresh

If you are using node (React / Redux / Universal JS) you can install npm i -S jwt-autorefresh.

This library schedules refresh of JWT tokens at a user calculated number of seconds prior to the access token expiring (based on the exp claim encoded in the token). It has an extensive test suite and checks for quite a few conditions to ensure any strange activity is accompanied by a descriptive message regarding misconfigurations from your environment.

Full example implementation

import autorefresh from 'jwt-autorefresh'

/** Events in your app that are triggered when your user becomes authorized or deauthorized. */
import { onAuthorize, onDeauthorize } from './events'

/** Your refresh token mechanism, returning a promise that resolves to the new access tokenFunction (library does not care about your method of persisting tokens) */
const refresh = () => {
  const init =  { method: 'POST'
                , headers: { 'Content-Type': `application/x-www-form-urlencoded` }
                , body: `refresh_token=${localStorage.refresh_token}&grant_type=refresh_token`
                }
  return fetch('/oauth/token', init)
    .then(res => res.json())
    .then(({ token_type, access_token, expires_in, refresh_token }) => {
      localStorage.access_token = access_token
      localStorage.refresh_token = refresh_token
      return access_token
    })
}

/** You supply a leadSeconds number or function that generates a number of seconds that the refresh should occur prior to the access token expiring */
const leadSeconds = () => {
  /** Generate random additional seconds (up to 30 in this case) to append to the lead time to ensure multiple clients dont schedule simultaneous refresh */
  const jitter = Math.floor(Math.random() * 30)

  /** Schedule autorefresh to occur 60 to 90 seconds prior to token expiration */
  return 60 + jitter
}

let start = autorefresh({ refresh, leadSeconds })
let cancel = () => {}
onAuthorize(access_token => {
  cancel()
  cancel = start(access_token)
})

onDeauthorize(() => cancel())

disclaimer: I am the maintainer


Today, lots of people opt for doing session management with JWTs without being aware of what they are giving up for the sake of perceived simplicity. My answer elaborates on the 2nd part of the questions:

What is the real benefit then? Why not have only one token (not JWT) and keep the expiration on the server?

Are there other options? Is using JWT not suited for this scenario?

JWTs are capable of supporting basic session management with some limitations. Being self-describing tokens, they don't require any state on the server-side. This makes them appealing. For instance, if the service doesn't have a persistence layer, it doesn't need to bring one in just for session management.

However, statelessness is also the leading cause of their shortcomings. Since they are only issued once with fixed content and expiration, you can't do things you would like to with a typical session management setup.

Namely, you can't invalidate them on-demand. This means you can't implement a secure logout as there is no way to expire already issued tokens. You also can't implement idle timeout for the same reason. One solution is to keep a blacklist, but that introduces state.

I wrote a post explaining these drawbacks in more detail. To be clear, you can work around these by adding more complexity (sliding sessions, refresh tokens, etc.)

As for other options, if your clients only interact with your service via a browser, I strongly recommend using a cookie-based session management solution. I also compiled a list authentication methods currently widely used on the web.


Ref - Refresh Expired JWT Example

Another alternative is that once the JWT has expired, the user/system will make a call to another url suppose /refreshtoken. Also along with this request the expired JWT should be passed. The Server will then return a new JWT which can be used by the user/system.

enter image description here


Below are the steps to do revoke your JWT access token:

1) When you do login, send 2 tokens (Access token, Refresh token) in response to client .
2) Access token will have less expiry time and Refresh will have long expiry time .
3) Client (Front end) will store refresh token in his local storage and access token in cookies.
4) Client will use access token for calling apis. But when it expires, pick the refresh token from local storage and call auth server api to get the new token.
5) Your auth server will have an api exposed which will accept refresh token and checks for its validity and return a new access token.
6) Once refresh token is expired, User will be logged out.

Please let me know if you need more details , I can share the code (Java + Spring boot) as well.


I actually implemented this in PHP using the Guzzle client to make a client library for the api, but the concept should work for other platforms.

Basically, I issue two tokens, a short (5 minute) one and a long one that expires after a week. The client library uses middleware to attempt one refresh of the short token if it receives a 401 response to some request. It will then try the original request again and if it was able to refresh gets the correct response, transparently to the user. If it failed, it will just send the 401 up to the user.

If the short token is expired, but still authentic and the long token is valid and authentic, it will refresh the short token using a special endpoint on the service that the long token authenticates (this is the only thing it can be used for). It will then use the short token to get a new long token, thereby extending it another week every time it refreshes the short token.

This approach also allows us to revoke access within at most 5 minutes, which is acceptable for our use without having to store a blacklist of tokens.

Late edit: Re-reading this months after it was fresh in my head, I should point out that you can revoke access when refreshing the short token because it gives an opportunity for more expensive calls (e.g. call to the database to see if the user has been banned) without paying for it on every single call to your service.


An alternative solution for invalidating JWTs, without any additional secure storage on the backend, is to implement a new jwt_version integer column on the users table. If the user wishes to log out or expire existing tokens, they simply increment the jwt_version field.

When generating a new JWT, encode the jwt_version into the JWT payload, optionally incrementing the value beforehand if the new JWT should replace all others.

When validating the JWT, the jwt_version field is compared alongside the user_id and authorisation is granted only if it matches.


Examples related to security

Monitoring the Full Disclosure mailinglist Two Page Login with Spring Security 3.2.x How to prevent a browser from storing passwords JWT authentication for ASP.NET Web API How to use a client certificate to authenticate and authorize in a Web API Disable-web-security in Chrome 48+ When you use 'badidea' or 'thisisunsafe' to bypass a Chrome certificate/HSTS error, does it only apply for the current site? How does Content Security Policy (CSP) work? How to prevent Screen Capture in Android Default SecurityProtocol in .NET 4.5

Examples related to authentication

Set cookies for cross origin requests How Spring Security Filter Chain works What are the main differences between JWT and OAuth authentication? http post - how to send Authorization header? ASP.NET Core Web API Authentication Token based authentication in Web API without any user interface Custom Authentication in ASP.Net-Core Basic Authentication Using JavaScript Adding ASP.NET MVC5 Identity Authentication to an existing project LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1

Examples related to jwt

jwt check if token expired Is it safe to store a JWT in localStorage with ReactJS? Unsupported Media Type in postman How Spring Security Filter Chain works JWT authentication for ASP.NET Web API What are the main differences between JWT and OAuth authentication? RS256 vs HS256: What's the difference? How to decode jwt token in javascript without using a library? How to decode JWT Token? How to destroy JWT Tokens on logout?