SoFunction
Updated on 2025-04-22

Redis implements session management and token authentication sample code

In modern web applications,Session ManagementandIdentity AuthenticationIt is the basis for implementing user login, permission management and other functions. Traditional session management is implemented by saving session information on the server side, but with the expansion of applications, especially in distributed systems, the limitations of this method gradually emerge.RedisAs a distributed cache system, it has high performance and high availability, and can well solve the problems of session management and token authentication in distributed environments.

This tutorial will introduce how to implement session management and token authentication based on Redis and Spring Boot to ensure that applications have good performance and scalability in high concurrency and distributed architectures.

1. Use scenarios

  • Distributed Systems: When the system is deployed on multiple service instances, the server's local session cannot be shared across instances, and Redis can be used as a centralized storage to help manage session information for all instances.
  • Stateless authentication: Based on the implementation of the token authentication mechanism, especially JWT (JSON Web Token), it is suitable for users to authenticate through the token after logging in, avoiding re-querying the database or reading the Session every time they request.
  • High concurrency scenarios: In the case of high concurrency, Redis's high throughput and low latency can ensure the efficiency of session management and authentication mechanisms.

2. Principle analysis

1. Session Management

Traditional session management determines the user's identity by saving the user's session status (Session) on the server and matching the server through the Session ID saved by the client (usually a browser). In a distributed environment, the local Session mechanism cannot guarantee cross-instance sharing, while Redis, as a centralized storage, can provide a cross-service instance session sharing mechanism.

2. Token certification

Token authentication, especially JWT-based authentication method, is a stateless authentication solution. Unlike the traditional Session mechanism, JWT encapsulates user information in a token and sends it to the client. The client carries the token for authentication in subsequent requests, and the server determines the user's identity by verifying the token. Redis can be used as a storage of the validity period of a token or a mapping with other user data.

3. Redis's role in session management and token authentication

  • Session Management: Store user's session information in Redis to ensure shared access to the session by different instances in the distributed system.
  • Token certification: Store the validity and user information of the token, or use it to store blacklisted tokens (deactivated or cancelled tokens).

3. Solution implementation

1. Environment configuration

First, inAdd Redis and Spring Security-related dependencies:

<dependencies>
    <!-- Spring Boot Web -->
    <dependency>
        <groupId></groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
    <!-- Redis -->
    <dependency>
        <groupId></groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>

    <!-- Spring Security -->
    <dependency>
        <groupId></groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

    <!-- JWT Token -->
    <dependency>
        <groupId></groupId>
        <artifactId>jjwt-api</artifactId>
        <version>0.11.2</version>
    </dependency>
    <dependency>
        <groupId></groupId>
        <artifactId>jjwt-impl</artifactId>
        <version>0.11.2</version>
    </dependency>
    <dependency>
        <groupId></groupId>
        <artifactId>jjwt-jackson</artifactId>
        <version>0.11.2</version>
    </dependency>
</dependencies>

existConfigure Redis in:

spring:
  redis:
    host: localhost
    port: 6379
    timeout: 6000ms

2. Redis session management implementation

In Spring Boot, we can manage session information through Redis. The following sample code shows how to use Redis to store user session information.

Configure Redis Serializer

In order to enable objects to be stored in Redis, we need to configure the serialization method of Redis.

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate&lt;String, Object&gt; redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate&lt;String, Object&gt; template = new RedisTemplate&lt;&gt;();
        (connectionFactory);
        
        // Set the serializer for Key and Value        (new StringRedisSerializer());
        (new GenericJackson2JsonRedisSerializer());
        
        return template;
    }
}

Use Redis to store Session information

We can store the session information into Redis after the user logs in.

@Service
public class SessionService {

    @Autowired
    private RedisTemplate&lt;String, Object&gt; redisTemplate;

    public void saveSession(String sessionId, Object sessionData) {
        ().set(sessionId, sessionData, 30, ); // The session is valid for 30 minutes    }

    public Object getSession(String sessionId) {
        return ().get(sessionId);
    }

    public void deleteSession(String sessionId) {
        (sessionId);
    }
}

3. Token authentication implementation

JWT generation and analysis

JWT is a stateless authentication method that encapsulates user information in a token and ensures the security of the token through digital signatures. We usejjwtlibrary to generate and parse JWT.

JWT Tools

@Service
public class JwtTokenProvider {

    private static final String SECRET_KEY = "yourSecretKey";

    // Generate tokens    public String generateToken(String username) {
        return ()
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(() + 3600000)) // Token valid for 1 hour                .signWith(SignatureAlgorithm.HS512, SECRET_KEY)
                .compact();
    }

    // parse Token    public String getUsernameFromToken(String token) {
        return ()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(token)
                .getBody()
                .getSubject();
    }

    // Verify that the token expires    public boolean isTokenExpired(String token) {
        Date expiration = ()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(token)
                .getBody()
                .getExpiration();
        return (new Date());
    }
}

JWT interceptor implementation

To verify the validity of the token on each request, we can verify it through the interceptor before the request reaches the controller.

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtTokenProvider jwtTokenProvider;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = getTokenFromRequest(request);
        
        if (token != null &amp;&amp; !(token)) {
            String username = (token);
            // Set authentication information in SecurityContext            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(username, null, new ArrayList&lt;&gt;());
            ().setAuthentication(authentication);
        }
        
        (request, response);
    }

    private String getTokenFromRequest(HttpServletRequest request) {
        String bearerToken = ("Authorization");
        if ((bearerToken) &amp;&amp; ("Bearer ")) {
            return (7);
        }
        return null;
    }
}

Add an interceptor to your Spring Security configuration

We need toJwtAuthenticationFilterAdd to Spring Security's filter chain.

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .authorizeRequests()
            .antMatchers("/login", "/register").permitAll()  // Login and registration requests do not require authentication            .anyRequest().authenticated()
            .and()
            .addFilterBefore(jwtAuthenticationFilter, );
    }
}

4. The combination of Token and Redis

To further enhance security, we can store the generated tokens in Redis and set an expiration time. When the token fails or the user logs out, remove it from Redis.

@Service
public class TokenService {

    @Autowired
    private RedisTemplate&lt;String, Object&gt; redisTemplate;
    @Autowired
    private JwtTokenProvider jwtTokenProvider;

    public String createToken(String username) {
        String token = (username);
        ().set(username, token, 1, );  // Tokens are stored in Redis, 1 hour expires        return token;
    }

    public boolean validateToken(String token) {
        String username = jwt
        String username = (token);
        String redisToken = (String) ().get(username);
        return (redisToken) &amp;amp;&amp;amp; !(token);
    }

    public void invalidateToken(String username) {
        (username);  // Remove Token from Redis    }
}

5. Login interface implementation

After the user logs in successfully, the token is generated and stored in Redis, and the token is returned to the client. The client carries this token in subsequent requests.

@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private AuthenticationManager authenticationManager;

    @PostMapping("/login")
    public ResponseEntity&lt;?&gt; login(@RequestBody LoginRequest loginRequest) {
        try {
            // Authenticated user            Authentication authentication = (
                new UsernamePasswordAuthenticationToken(
                    (), ()));
            
            ().setAuthentication(authentication);
            
            // Generate tokens and store them to Redis            String token = (());
            
            return (new JwtResponse(token));
        } catch (AuthenticationException e) {
            return ().body("Authentication failed");
        }
    }

    @PostMapping("/logout")
    public ResponseEntity&lt;?&gt; logout(HttpServletRequest request) {
        String token = getTokenFromRequest(request);
        if (token != null) {
            String username = (token);
            (username);  // Remove Token from Redis        }
        return ("Logout successful");
    }

    private String getTokenFromRequest(HttpServletRequest request) {
        String bearerToken = ("Authorization");
        if ((bearerToken) &amp;&amp; ("Bearer ")) {
            return (7);
        }
        return null;
    }
}

6. Request process example

  • User login: The user provides the user name and password, through/auth/loginLog in to the interface. After success, the server generates a JWT Token and saves it to Redis, and returns it to the client.
  • Token carrying request: The client puts the token in subsequent requestsAuthorizationIn the header, send to the server. After receiving the request, the server parses the token through JWT to verify the validity.
  • Log out operation: When the user logs out, the front-end requests/auth/logoutInterface, the server removes the user's token from Redis, and the token is invalid.

4. Redis session management and Token authentication effects

  • High efficiency performance: Redis's high concurrent reading and writing ability ensures the efficiency of session storage and Token verification in high concurrency scenarios.
  • Distributed support: Using Redis as centralized storage ensures that session data is shared in multi-instance or distributed deployment environments, avoiding the limitations of local sessions.
  • Security enhancement: Through Redis storage tokens and the validity period control of tokens, the token failure processing can be quickly realized, enhancing security.

5. Summary

Redis can not only solve the problem of session sharing in a distributed environment, but also achieve high-performance processing of Token authentication through efficient storage and fast reading. In Spring Boot, using a solution combining Redis and JWT provides powerful authentication and authorization support for distributed architectures.

This is the article about the example code for Redis to implement session management and token authentication. For more related Redis session management and token authentication, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!