Last updated: 2024-10-10
Refresh Tokens with Spring Boot
In the previous article, we have already looked at how we protect our REST API using JWTs. How can we also integrate refresh tokens into our application?
Background on refresh tokens
In many scenarios, a user should only validate once and then be able to access a system over a longer period of days or months. Theoretically, the runtime of the JWTs could be increased for this - but as the tokens cannot be cancelled, this is generally not recommended.
Refresh tokens, on the other hand, are stored in the database and are bound to a user, so that a higher degree of control is provided. The user or organisation keeps an overview of who has access to the system. If necessary, all tokens of a user can be removed. This also allows us to reduce the lifetime of the JWTs to the recommended duration of less than 5 minutes.
Backend extensions
To integrate refresh tokens into our application, we first need a table that is linked to the user table. At least two fields are required in the table, one for the token and one for its validity. This can be extended further if required.
A simple table for the refresh tokens
A new service JwtRefreshTokenService
provides the methods for issuing and validating the refresh tokens.
The required service
This already allows us to integrate the new service into our existing AuthenticationResource
. The /authenticate
endpoint now needs to return the additional token in the response. We add the /refresh
endpoint in order to deliver a fresh JWT when required.
Extension of our AuthenticationResource
In our chosen approach, the refresh tokens are not invalidated and can thus be used unlimited times until the end of their lifetime. With this our backend is already complete!
Angular integration
If our Angular frontend has already implemented authentication using JWT, we now receive the refresh token directly after the authentication. This we should now also add to our local storage.
Saving a refresh token after login
Each browser tab should refresh the JWT once when it is opened and then at regular intervals if necessary. This is done using the following method.
Requesting a new JWT when expiration is near
This renews the JWT in good time before it expires. If the error code 401
is returned when /refresh
is called, all local tokens are deleted and the user must reauthenticate with username and password.
Bootify offers a tool for creating modern Spring Boot applications in the browser. In the Free plan, you can create your own database schema with an optional frontend. A complex security setup can be defined in the Professional plan. A config for JWT including a table for the refresh tokens can be specified here, which then is integrated into an Angular frontend.
See Pricing
or read quickstart