Redis as Token Store Spring Boot Oauth2

 

In this article we’ll use redis as token store instead of in memory token store.

1. Dependency

Add redis dependency on pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2. Configuration Properties

Add redis configuration properties on application.properties file

spring.redis.host=localhost
spring.redis.password=
spring.redis.port=6379

3. Create a bean

Create a bean in any class that has @Configuration in it.

    @Bean    
    public TokenStore redisTokenStore() {
        return new RedisTokenStore(redisConnectionFactory);
    }

You’ll have to @Autowire RedisConnectionFactory on that class. Spring will automatically inject RedisConnectionFactory bean.

4. Register Redis as TokenStore

In your class that extends AuthorizationServerConfigurerAdapter , register redis as your tokenstore

 @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager)
                .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
                .tokenStore(redisTokenStore()) // registering redisTokenStore bean
                .tokenEnhancer(new CustomTokenEnhancer());
    }

5. Install redis on your machine

Now install redis on your server/local machine

sudo apt-get install redis-server

To test if redis is installed successfully, open Terminal and enter

redis-cli

Now if you send a command ping you’ll get PONG in reply. That’s how you know redis is installed successfully.

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *