eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

Course – LSS – NPI (cat=Spring Security)
announcement - icon

If you're working on a Spring Security (and especially an OAuth) implementation, definitely have a look at the Learn Spring Security course:

>> LEARN SPRING SECURITY

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

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

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 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:

spring oauth with redis. image with all 3 services running

Now, let’s navigate to http://127.0.0.1:8080/articles. This page will redirect us to the login page:

spring oauth with redis. login page image

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:

spring oauth with redis, image of page with articles, after successful login

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:

spring oauth with redis. image of the stored data in redis, after login

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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – LSS – NPI (cat=Security/Spring Security)
announcement - icon

I just announced the new Learn Spring Security course, including the full material focused on the new OAuth2 stack in Spring Security:

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)