Integrating Spring Boot Security with Redis for Cached User Authentication

This article explains how to use Spring Boot Security for authentication and improve performance by caching user details in Redis, covering dependency setup, security configuration, Redis integration, testing endpoints, and optimization tips for a robust backend authentication solution.

Selected Java Interview Questions
Selected Java Interview Questions
Selected Java Interview Questions
Integrating Spring Boot Security with Redis for Cached User Authentication

In web applications, security is crucial; Spring Security handles authentication and authorization, and caching user data in Redis can reduce database load and improve performance.

Spring Boot Security Overview – Spring Boot Security is a sub‑project of the Spring framework that provides flexible security features such as authentication, authorization, and session management, easily integrated with Spring Boot applications.

Integrating Spring Boot Security

<!-- pom.xml -->
<dependencies>
    <!-- Spring Boot Security -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

    <!-- Spring Data Redis -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
</dependencies>

Configure Spring Security by extending WebSecurityConfigurerAdapter and defining beans for UserDetailsService and PasswordEncoder:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails user = User.withUsername("user")
                .password(passwordEncoder().encode("password"))
                .roles("USER")
                .build();
        return new InMemoryUserDetailsManager(user);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService())
            .passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/public/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin().permitAll()
                .and()
                .logout().permitAll();
    }
}

Redis Configuration – Add Redis connection properties to application.properties:

# application.properties

# Redis configuration
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=###

Replace the in‑memory user store with RedisUserDetailsManager to cache users in Redis:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.RedisUserDetailsManager;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    // ... other configurations

    @Bean
    public UserDetailsService userDetailsService(RedisConnectionFactory redisConnectionFactory) {
        RedisUserDetailsManager userDetailsManager = new RedisUserDetailsManager(redisConnectionFactory);
        UserDetails user = User.withUsername("user")
                .password(passwordEncoder().encode("password"))
                .roles("USER")
                .build();
        userDetailsManager.createUser(user);
        return userDetailsManager;
    }

    // ... other configurations
}

Update the authentication manager to use the Redis‑backed userDetailsManager:

@Autowired
private UserDetailsManager userDetailsManager;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsManager)
        .passwordEncoder(passwordEncoder());
}

Testing the Authentication – Create a simple controller with public and private endpoints:

@RestController
public class TestController {

    @GetMapping("/public/hello")
    public String helloPublic() {
        return "Hello, this is a public page!";
    }

    @GetMapping("/private/hello")
    public String helloPrivate() {
        return "Hello, this is a private page!";
    }
}

The public endpoint is accessible without login, while the private endpoint requires authentication, demonstrating that user data is now retrieved from Redis.

Performance Optimization & Extensions

Adjust Redis cache expiration and eviction policies to suit application load.

Consider Redis cluster deployment for high‑concurrency scenarios.

Implement custom UserDetailsService to store users in databases or other stores.

Integrate Single Sign‑On (SSO) for cross‑system authentication.

Conclusion

The guide shows how to secure a Spring Boot application with Spring Security, cache user details in Redis using RedisUserDetailsManager, and verify the setup with simple endpoints, resulting in faster authentication and a more scalable security architecture.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

javaredisSpring BootAuthentication
Selected Java Interview Questions
Written by

Selected Java Interview Questions

A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.