简体   繁体   中英

JWT in Cookies - do I need a refresh token?

I'm implementing security for my React SPA using Spring Security on the backend. After a lot of reading, I opted for the following approach:

  • HTTPS everywhere
  • POST /login takes credentials returns JWT_TOKEN & XSRF_TOKEN in cookie form. I build the JWT_TOKEN myself whereas Spring Security handles the XSRF_TOKEN. Both cookies are Secured and SameSite=Strict. The JWT token is HttpOnly.
  • Subsequent API calls require the X-XSRF-TOKEN header. This is read from the aforementionned cookie. Both are sent and Spring Security compares them. JWT is automatically sent and checked in a Filter.
  • Every time a XSRF token is used, Spring Security generates a new one to prevent session-fixation attacks
  • XSS protections are applied by Spring Security

So now I'm wondering about refresh tokens. I'm reading a lot of contradictory info out there. Do I need them with this setup? If so how best to handle this?

Many Thanks

In general, as its name says, the refresh token changes from one token to another. Typically they are used in OAuth protocol-based authentication. They are useful when an access token has expired, but the user's session is still valid.

First, JWTs are a great choice for access tokens. They have claims that match the access tokens requirements, such as: exp , iat , jti , sub , etc. But, when using a cookie-based authentication there is no need for access tokens and possibly no need for JWT.

As you said, your JWT_TOKEN is being set as an HttpOnly cookie, which means that only the server has access to it. JWT is useful for sharing the initial state between the client and server, and vice-versa. If your server is just taking it to look up the database, you don't need a JWT, you are just using a session concept, and keeping session data on a JWT may not be a good practice.

Second, if your authenticated cookie data will live at /login and die at /logout , there is no need for refresh tokens. Refresh tokens are an exchange key for short-life access tokens. Instead, your cookies keep the session live and don't need to be exchanged by something else.

For example, if the user uses the /login route to exchange your username and password for one short life access_token . He may need the refresh_token to get a new access_token without needing to send his username and password again.

If you are using the OAuth protocol or similar, refresh tokens are essential to provide a more seamless experience for your users and avoid the inconvenience of repeatedly having to re-enter their credentials. But even on OAuth, they are not mandatory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM