Configure expiration time for access tokens in Spring Authorization Server

A big advantage of OAuth2 is that it can allow us to limit the amount of time a request with a particular access token is allowed to use resources. An access token will determine its expiration time, API resources will rely on this expiration time to decide whether to allow a Client Application to continue accessing resources or not? Using Spring Authorization Server to implement Authorization Server, how to configure expiration time for an access token? We will find out together in this tutorial!

The first thing you need to know is, we will use the TokenSettings class of the Spring Authorization Server to configure some information related to the access token. Currently, you can configure expiration time, reuse refresh token, refresh token expiration time, ID token signature algorithm.

To configure expiration time at the system level, apply it to all clients in the system, you can define a bean of TokenSettings as follows:

Then in the declaration of each RegisteredClient, you declare more information about tokenSettings as follows:

I’m declaring RegisteredClient with TokenSettings in a Java class file, if you define it in 2 different class files, you can use the @Autowired annotation, then inject the TokenSettings bean and then use it in the RegisteredClient’s tokenSettings() method.

If you want a specific expiration time for each RegisteredClient, please initialize new and use the TokenSettings object for that RegisteredClient object.

Run the example in the tutorial Implement OAuth Authorization Server using Spring Authorization Server with above TokenSettings configuration:

then parse the content of the access token using https://jwt.io/, you will see when the issued access token is issued at:

the expiration time will be:

The default expiration time of an access token in the Spring Authorization Server is 5 minutes!

2 thoughts on “Configure expiration time for access tokens in Spring Authorization Server

  1. Thanks Khanh Nguyen. if possible can you make a tutorial on JdbsRegisteredClient. Which will help a lot. Thanks once again.

Add Comment