
1. Overview
The default implementation of Spring Authorization Server stores everything in memory. Things like RegisteredClient, Token stores, Authorization states, and more are all created and deleted every time the JVM starts/stops. This is beneficial in certain cases, such as demos and testing. However, it becomes a problem in real-life applications because it doesn’t work with horizontal scaling, restarts, and other similar scenarios.
To overcome this issue, Spring offers methods for implementing the Core Services of Spring Authorization Service with Redis. This way, we can have persistence and durability for tokens and registered clients. Additionally, we can enjoy better quality and security, with access to manage the tokens. We can scale the Authorization Server, provide observability and event sourcing, and provide access to revoke tokens across multiple nodes, among other benefits.
In this article, we’re going to explore how we can implement the Core Services of Spring Authorization Service with Redis. We’ll examine the components that need to be changed or added and provide code examples to achieve this. We’ll be using an embedded Redis Server for demonstration purposes. However, everything should work the same way for container-based or deployed instances.
2. Base Project
For this tutorial, we’re going to base the demo code on the existing Spring Security OAuth project, which stores everything in memory. Then, we’ll introduce the Core Services of Spring Authorization Service with Redis.
The existing project is a REST API that provides a list of articles. But the endpoint is secured and needs authentication and authorizations, as described in the linked article. We won’t be making any changes to the service per se, in the scope of the current tutorial.
2.1. Project Structure
The base project contains three modules:
- The Authorization Server serves as an authentication source for both the article resources and client servers
- The Resource Server offers the list of articles after it validates authorization against the Authorization Server
- The Client Server is a REST API client that fetches the articles after authenticating the user and makes an authorized request to the Resource Server
In this article, we’ll use the same code as in the base project with some changes in the Authorization Server.
2.2. Dependencies
First, let’s define the common version for Spring dependencies to use in all modules. To achieve that, all modules will use a common parent that, in turn, uses spring-boot-starter-parent as its parent:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.5.0</version>
</parent>
The other version we need to mention is the embedded Redis Server dependency, to use in the Authorization Server:
<dependency>
<groupId>com.github.codemonstur</groupId>
<artifactId>embedded-redis</artifactId>
<version>1.4.2</version>
</dependency>
3. Spring Authorization Server With Redis
Spring Authorization Server, by default, uses in-memory implementations for:
- RegisteredClientRepository
- Token stores
- Authorization consents
- Authorization states
This is beneficial in certain scenarios, particularly when we need to act quickly without requiring long-term storage. Such scenarios could be running tests, demonstration purposes, and others. But if the use case is more complex, with requirements for long-term storage, the ability to scale, and requirements for monitoring, then the Authorization Server needs to be able to store things in a database.
Spring offers this option to implement the Core Services of Spring Authorization Service with Redis. To do that, we need to:
- Define the entity model
- Create Spring Data repositories
- Implement core services
- Configure core services
3.1. Entity Model of the Authorization Service With Redis
First, we need to define some entities to represent the core components: RegisteredClient, OAuth2Authorization, and OAuth2AuthorizationConsent. We broke the OAuth2Authorization class down based on the authorization grant type. Let’s examine the entities we’ll be creating:
- Registered Client Entity (OAuth2RegisteredClient) is used to persist information mapped from the RegisteredClient
- Authorization Consent Entity (OAuth2UserConsent) is used to persist information mapped from the OAuth2AuthorizationConsent
- Authorization Grant Base Entity (OAuth2AuthorizationGrantAuthorization) is the base entity to persist information mapped to OAuth2Authorization and has common attributes for each authorization grant type
- Authorization Code Grant Entity for OAuth 2.0 (OAuth2AuthorizationCodeGrantAuthorization) defines additional attributes for the OAuth 2.0 “authorization_code” grant type
- Authorization Code Grant Entity for OpenID Connect 1.0 (OidcAuthorizationCodeGrantAuthorization) defines additional attributes for the OpenID Connect 1.0 “authorization_code” grant type
- Client Credentials Grant Entity (OAuth2ClientCredentialsGrantAuthorization) defines additional attributes for the “client_credentials” grant type
- Device Code Grant Entity (OAuth2DeviceCodeGrantAuthorization) defines additional attributes for the “urn:ietf:params:oauth:grant-type:device_code” grant type
- Token Exchange Grant Entity (OAuth2TokenExchangeGrantAuthorization) defines additional attributes for the “urn:ietf:params:oauth:grant-type:token-exchange” grant type
We can find the implementation code of the entity files over on GitHub.
3.2. Spring Data Repositories of the Authorization Service With Redis
Then, we create the minimal set of repositories that we need to implement the Core Services of Spring Authorization Service with Redis. Those are:
- Registered Client Repository (OAuth2RegisteredClientRepository) to find the OAuth2RegisteredClient by id or clientId
- Authorization Consent Repository (OAuth2UserConsentRepository) to find and delete any OAuth2UserConsent record by the registeredClientId and principalName
- Authorization Grant Repository (OAuth2AuthorizationGrantAuthorizationRepository) to find an OAuth2AuthorizationGrantAuthorization by id, state, deviceCode, etc, depending on the grant type
We can find the implementation code of the repositories over on GitHub.
3.3. Core Services of the Authorization Service With Redis
Similarly, we want to construct the services corresponding to the previous Core Services of the Authorization Service. These Core Services are:
- Model Mapper (ModelMapper) is not a core service, but it’s one we’ll use in all the following core services to do mappings between entity objects and domain objects
- Registered Client Repository (RedisRegisteredClientRepository) combines OAuth2RegisteredClientRepository, OAuth2RegisteredClient, and the ModelMapper classes to persist RegisteredClient objects
- Authorization Consent Service (RedisOAuth2AuthorizationConsentService) combines OAuth2UserConsentRepository, OAuth2UserConsent and the ModelMapper classes to persist OAuth2AuthorizationConsent objects
- Authorization Service (RedisOAuth2AuthorizationService) combines OAuth2AuthorizationGrantAuthorizationRepository, OAuth2AuthorizationGrantAuthorization and the ModelMapper classes to persist OAuth2Authorization objects
We can find the implementation code of the services over on GitHub.
3.4. Spring Configuration of the Authorization Service With Redis
Last, we need to create the Spring Configuration files that will enable the Core Services of Spring Authorization Service with Redis.
The SecurityConfig class should contain the same beans as in the base project. The user credentials we register and will use later in the demonstration are username “admin”, password “password”. Let’s look at the configuration for Redis:
@Configuration(proxyBeanMethods = false)
@EnableRedisRepositories
public class RedisConfig {
// fields omitted
@PostConstruct
public void postConstruct() throws IOException {
redisServer.start();
}
@PreDestroy
public void preDestroy() throws IOException {
redisServer.stop();
}
@Bean
@Order(1)
public JedisConnectionFactory redisConnectionFactory() {
RedisStandaloneConfiguration redisStandaloneConfiguration
= new RedisStandaloneConfiguration(redisHost, redisPort);
return new JedisConnectionFactory(redisStandaloneConfiguration);
}
@Bean
@Order(2)
public RedisTemplate<?, ?> redisTemplate(JedisConnectionFactory connectionFactory) {
RedisTemplate<byte[], byte[]> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
return template;
}
@Bean
@Order(3)
public RedisCustomConversions redisCustomConversions() {
return new RedisCustomConversions(
Arrays.asList(
new UsernamePasswordAuthenticationTokenToBytesConverter(),
new BytesToUsernamePasswordAuthenticationTokenConverter(),
new OAuth2AuthorizationRequestToBytesConverter(),
new BytesToOAuth2AuthorizationRequestConverter(),
new ClaimsHolderToBytesConverter(),
new BytesToClaimsHolderConverter()));
}
@Bean
@Order(4)
public RedisRegisteredClientRepository registeredClientRepository(
OAuth2RegisteredClientRepository registeredClientRepository) {
RedisRegisteredClientRepository redisRegisteredClientRepository
= new RedisRegisteredClientRepository(registeredClientRepository);
redisRegisteredClientRepository.save(RegisteredClients.messagingClient());
return redisRegisteredClientRepository;
}
@Bean
@Order(5)
public RedisOAuth2AuthorizationService authorizationService(
RegisteredClientRepository registeredClientRepository,
OAuth2AuthorizationGrantAuthorizationRepository authorizationGrantAuthorizationRepository) {
return new RedisOAuth2AuthorizationService(registeredClientRepository,
authorizationGrantAuthorizationRepository);
}
@Bean
@Order(6)
public RedisOAuth2AuthorizationConsentService authorizationConsentService(
OAuth2UserConsentRepository userConsentRepository) {
return new RedisOAuth2AuthorizationConsentService(userConsentRepository);
}
}
The RedisConfig class provides the Spring beans for Redis and the Core Components of the Authorization Service with Redis:
- @PostConstruct and @PreDestroy annotations are used to start and stop the embedded Redis Server
- JedisConnectionFactory and RedisTemplate beans are used for connecting to Redis
- The RedisCustomConversions bean is needed for the Object-to-hash conversions needed for persisting to Redis
- RedisRegisteredClientRepository is used to set the registeredClientRepository bean and then register a client, as we’ll be explained in the next section
- RedisOAuth2AuthorizationService is registered as the authorizationService bean, with the appropriate repositories set
- Similarly, RedisOAuth2AuthorizationConsentService is registered as the authorizationConsentService bean
3.5. Registered Clients
When we use Spring OAuth Security with the default, in-memory persistence, we can define the registered clients using properties. This is a built-in feature for the Spring Authorization Service, starting from version 3.1.0, that uses the OAuth2AuthorizationServerProperties class.
But in our case, this is not supported by default because we implement the Core Services of Spring Authorization Service with Redis, and more specifically, we use a custom RegisteredClientRepository.
We can follow different approaches to resolve this, like using the OAuth2AuthorizationServerProperties class and doing the mapping and storage to the custom repository ourselves, using hardcoded values directly, and more. Since this is a tutorial, we’ll go with the less complex way, which is to use hardcoded values and store the RegisteredClient in the RedisRegisteredClientRepository directly, in the config (as shown in the previous section).
Let’s create a RegisteredClient using code:
public class RegisteredClients {
public static RegisteredClient messagingClient() {
return RegisteredClient.withId(UUID.randomUUID().toString())
.clientId("articles-client")
.clientSecret("{noop}secret")
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
.authorizationGrantType(AuthorizationGrantType.DEVICE_CODE)
.redirectUri("http://127.0.0.1:8080/login/oauth2/code/articles-client-oidc")
.redirectUri("http://127.0.0.1:8080/authorized")
.postLogoutRedirectUri("http://127.0.0.1:9000/login")
.scope(OidcScopes.OPENID)
.scope("articles.read")
.build();
}
}
This configuration should be familiar, since it is a copy of the property-based registered clients from the base project. Note that we use all four authorization grant types we created entities for.
4. Demonstration of the Authorization Service With Redis
Let’s see how we can get access to the articles resource. First thing is to start all three modules. In our case, we’re using IntelliJ to do that:
Now, let’s navigate to http://127.0.0.1:8080/articles. This page will redirect us to the login page:
On this page, a user can select to authenticate themselves either by clicking on articles-client-authorization-code or articles-client-oidc. In both cases, they will need to provide their username and password (“admin”, “password”, as set in the UserDetailsService bean).
This way, they authenticate to the Authorization Server and acquire the privileges for accessing the articles-client. If the user selects the first option to authenticate, they are redirected back to this page after a successful login and must click on the second link to navigate to the articles page. If the user selected the second option, then all is done automatically:
In the image, we can see that after a successful login, the user has access to the resources. We can also see the cookie added to the browser.
One more thing to note is that, since we implemented the Core Services of Spring Authorization Service with Redis, we can now see that the Redis server has information about the live sessions and more:
The oauth2_registered_client objects were the only ones that existed in Redis before login. The rest are all data that we store after a successful login.
5. Conclusion
In this article, we talked about the Core Services of Spring Authorization Service with Redis. We reviewed the components that need to be modified to switch from the default in-memory storage to using Redis. Finally, we observed the process of authenticating an authorized user to gain access to the resource and how the Authorization Server stores tokens in Redis.
As always, all the source code used in the examples is available over on GitHub.
The post Implementing the Core Services of Spring Authorization Server with Redis first appeared on Baeldung.





