JWT refresh token flow

181,417

Solution 1

Assuming that this is about OAuth 2.0 since it is about JWTs and refresh tokens...:

  1. just like an access token, in principle a refresh token can be anything including all of the options you describe; a JWT could be used when the Authorization Server wants to be stateless or wants to enforce some sort of "proof-of-possession" semantics on to the client presenting it; note that a refresh token differs from an access token in that it is not presented to a Resource Server but only to the Authorization Server that issued it in the first place, so the self-contained validation optimization for JWTs-as-access-tokens does not hold for refresh tokens

  2. that depends on the security/access of the database; if the database can be accessed by other parties/servers/applications/users, then yes (but your mileage may vary with where and how you store the encryption key...)

  3. an Authorization Server may issue both access tokens and refresh tokens at the same time, depending on the grant that is used by the client to obtain them; the spec contains the details and options on each of the standardized grants

Solution 2

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

  1. When you do log in, send 2 tokens (Access token, Refresh token) in response to the client.
  2. The access token will have less expiry time and Refresh will have long expiry time.
  3. The client (Front end) will store refresh token in his local storage and access token in cookies.
  4. The client will use an access token for calling APIs. But when it expires, you call auth server API to get the new token (refresh token is automatically added to http request since it's stored in cookies).
  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 the refresh token is expired, the User will be logged out.

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

For your questions:

Q1: It's another JWT with fewer claims put in with long expiry time.

Q2: It won't be in a database. The backend will not store anywhere. They will just decrypt the token with private/public key and validate it with its expiry time also.

Q3: Yes, Correct

Solution 3

Based in this implementation with Node.js of JWT with refresh token:

  1. In this case they use a uid and it's not a JWT. When they refresh the token they send the refresh token and the user. If you implement it as a JWT, you don't need to send the user, because it would be inside the JWT.

  2. They implement this in a separate document (table). It makes sense to me because a user can be logged in in different client applications and it could have a refresh token by app. If the user lose a device with one app installed, the refresh token of that device could be invalidated without affecting the other logged in devices.

  3. In this implementation, it response to the log in method with both, access token and refresh token. It seems correct to me.

Solution 4

The refresh token flow is described in the OAuth 2.0 specification document.

  +--------+                                           +---------------+
  |        |--(A)------- Authorization Grant --------->|               |
  |        |                                           |               |
  |        |<-(B)----------- Access Token -------------|               |
  |        |               & Refresh Token             |               |
  |        |                                           |               |
  |        |                            +----------+   |               |
  |        |--(C)---- Access Token ---->|          |   |               |
  |        |                            |          |   |               |
  |        |<-(D)- Protected Resource --| Resource |   | Authorization |
  | Client |                            |  Server  |   |     Server    |
  |        |--(E)---- Access Token ---->|          |   |               |
  |        |                            |          |   |               |
  |        |<-(F)- Invalid Token Error -|          |   |               |
  |        |                            +----------+   |               |
  |        |                                           |               |
  |        |--(G)----------- Refresh Token ----------->|               |
  |        |                                           |               |
  |        |<-(H)----------- Access Token -------------|               |
  +--------+           & Optional Refresh Token        +---------------+
  
  
  (A)  The client requests an access token by authenticating with the
       authorization server and presenting an authorization grant.
  
  (B)  The authorization server authenticates the client and validates
       the authorization grant, and if valid, issues an access token
       and a refresh token.
  
  (C)  The client makes a protected resource request to the resource
       server by presenting the access token.
  
  (D)  The resource server validates the access token, and if valid,
       serves the request.
  
  (E)  Steps (C) and (D) repeat until the access token expires.  If the
       client knows the access token expired, it skips to step (G);
       otherwise, it makes another protected resource request.
  
  (F)  Since the access token is invalid, the resource server returns
       an invalid token error.
  
  (G)  The client requests a new access token by authenticating with
       the authorization server and presenting the refresh token.  The
       client authentication requirements are based on the client type
       and on the authorization server policies.
  
  (H)  The authorization server authenticates the client and validates
       the refresh token, and if valid, issues a new access token (and,
       optionally, a new refresh token).

Regarding your questions:

  1. It is another JWT
  2. The refresh token has to be stored on the server side
  3. Yes
Share:
181,417

Related videos on Youtube

jtmarmon
Author by

jtmarmon

Updated on July 08, 2022

Comments

  • jtmarmon
    jtmarmon almost 2 years

    I'm building a mobile app and am using JWT for authentication.

    It seems like the best way to do this is to pair the JWT access token with a refresh token so that I can expire the access token as frequently as I want.

    1. What does a refresh token look like? Is it a random string? Is that string encrypted? Is it another JWT?
    2. The refresh token would be stored in the database on the user model for access, correct? It seems like it should be encrypted in this case
    3. Would I sent the refresh token back after a user login, and then have the client access a separate route to retrieve an access-token?
    • gwentech
      gwentech over 9 years
      Note, if you are using refresh tokens you should provide an ability for users to invalidate them on the UI. It is also recommended to automatically expire them if they are not used for example for a month.
  • Rohmer
    Rohmer almost 7 years
    2. You should store a hash of the refresh token in your database and then compare the hash of the user's refresh token with your stored hash. The rule of "don't store plain text passwords in your database" follows here. Consider a token like a random password that you made for the user.
  • ozanmuyes
    ozanmuyes almost 6 years
    By saying "1) In this case they use a uid..." did you mean UUID?
  • Tnc Andrei
    Tnc Andrei over 5 years
    I think the JWT should be stored in localStorage and the refreshToken should be stored in a httpOnly. The refreshToekn can be used to get a new JWT so it has to be handled with extra caution.
  • Jay
    Jay about 5 years
    Thanks what do you mean by storing in httpOnly? Why not store both in localStorage?
  • user2010955
    user2010955 about 5 years
    i'm missing the benefits of using the refresh token, wouldn't be the same to extend the validity of the access token?
  • shadow0359
    shadow0359 almost 5 years
    @Jay According to the Microsoft Developer Network, HttpOnly is an additional flag included in a Set-Cookie HTTP response header. Using the HttpOnly flag when generating a cookie helps mitigate the risk of client side script accessing the protected cookie (if the browser supports it).
  • shadow0359
    shadow0359 almost 5 years
    @user2010955 access token will be sent by the client on every subsequent request , which means the probability someone capturing is high.
  • Joseph Persie III
    Joseph Persie III almost 5 years
    The issue with storing the refreshtoken as a cookie as well is that although it's more secure than localstorage, it too will be sent over wire on every subsequent request, increasing the probability of compromise of the refreshtoken. Auth0 recommends to store the refresh token in memory only if there is no backend on the client application as opposed to storing it in localstorage which is vulnerable to XSS. auth0.com/docs/security/store-tokens#if-no-backend-is-presen‌​t
  • danipenaperez
    danipenaperez almost 5 years
    I agree with @Tnc Andrei. If you not store the refresh token, you will never be able to invalidate to obtain new access token until the refresh token expired. I think it is better approach.
  • Jai Sharma
    Jai Sharma almost 5 years
    #2 is highly inaccurate. A refresh token HAS to be stored on the server side. You shouldn't leverage the "self-contained" property of JWT for a refresh token. Doing so leaves you with no way to revoke refresh tokens other than changing your private key.
  • adonese
    adonese over 4 years
    What about this simpler implementation - Issue JWT - send the older JWT when you want to refresh - (you can check iat with window) - reissue a new one based on the previous one
  • Brenno Costa
    Brenno Costa over 4 years
    @adonese by sending only the JWT you mean to have the refresh_token inside it? If so, OAuth RFC 6749 explicitly says to not send refresh_token to the resource server (and the JWT is sent to the resource servers): tools.ietf.org/html/rfc6749#section-1.5
  • Vishnu Dahatonde
    Vishnu Dahatonde over 4 years
    #Bhupinder, can you share the Java spring boot implementation you mentioned?
  • Bhupinder Singh
    Bhupinder Singh over 4 years
    @VishnuDahatonde, vishnu-dahatonde, Here is the link: github.com/BhupinderSingh03/microService
  • Bhumil Sarvaiya
    Bhumil Sarvaiya over 4 years
    Also, If you want to provide more security, also perform refresh token rotation. The importance of this is already mentioned in the ITEF RFC 6749. If implemented correctly, this can also help in identifying the token theft scenario, i.e. refresh token been stolen by an attacker. If you are looking for a better explanation, head over to this link
  • Jeeva J
    Jeeva J over 4 years
    When I read the following details from jwt, they have mentioned that refresh token should not be leaked to the client, since the hacker will get new access token based on the refresh token. Do we have any alternate? auth0.com/blog/…
  • Subbu
    Subbu about 4 years
    @JaiSharma-If the server stored the refresh token, how will the client request for a new access token when it expires as the client wont have the refresh token. Now do we need another api to fetch the refresh token for a logged in user then? Kindly clarify how would the process work in this case.
  • Franklin Innocent F
    Franklin Innocent F almost 4 years
    How do i get refresh token. Please share some sample code for PHP.
  • Robin Huy
    Robin Huy over 3 years
    How to implement feature allow user to force logout all devices if we don't store Access Token or Refresh Token on Server?
  • Sean Ch
    Sean Ch over 3 years
    as mentioned #2 is absolutely off the point.
  • ssamko
    ssamko over 2 years
    What is the security risk to have both Access and Refresh Token handling on resource server ?
  • Fouad
    Fouad over 2 years
    I do recommend following this link to secure the JWT token and refresh token on the front-end.
  • heathscliff
    heathscliff over 2 years
    To implement the refresh token is the same way like we create the access token? But, we create the refresh token with the long expiry time?
  • uberrebu
    uberrebu over 2 years
    can't an attacker get both the access token and refresh token from user's computer and use that to generate new access token to gain access as well? where is the protection here?!?
  • Noobie3001
    Noobie3001 over 2 years
    If the backend doesn't store the refresh token how does it get revoked?
  • rzlvmp
    rzlvmp almost 2 years
    Couple misunderstandings in this answer and comments. 1. (IMPORtANT) Both refresh and access token should be stored in cookies (ideally with HttpOnly flag). LocalStorage shouldn't be used for sensitive data, 2. It is not necessary to store both tokens at backend DBs (one of main advantages of JWT is ability to authenticate without access to DB. That allow to decrease DB overlaod). But if you don't store refresh tokens in DB one possible way to invalidate one token is change secret key and invalidate all tokens (all users will be logged out). For example github doing this trick sometimes