SpringBoot/Security使用Redis存储Session,超时时间设置

spring boot在使用redis共享session的情况下设置session过期时间 - 哔哩哔哩 (bilibili.com)

EnableRedisHttpSession注解介绍_maxinactiveintervalinseconds-CSDN博客

springboot redis 配置过期时间和刷新时间 spring session redis过期时间_archangle的技术博客_51CTO博客

EnableRedisHttpSession怎么设置过期时间_mob64ca12f86e32的技术博客_51CTO博客 

现状:spring boot项目,使用redisson将spring session存入redis中,过期时间为默认的30分钟。

需求:延长session过期时间

一开始我认为只修改yml文件中的server.servlet.session.timeout=60m就行了,但是发现redis中的过期时间还是1800s。

后来想到既然session是redis管理是不是需要修改redis相关的配置,然后查到了@EnableRedissonHttpSession注解,使用这个注解后spring boot中的server.servlet.session.timeout就失效了,默认的1800s也是这个注解来设置的:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Import(RedissonHttpSessionConfiguration.class)
@Configuration
public @interface EnableRedissonHttpSession {

    int maxInactiveIntervalInSeconds() default MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS;//1800

    String keyPrefix() default "";

}

所以可以在注解上配置过期时间来完成我们的需求:@EnableRedissonHttpSession(maxInactiveIntervalInSeconds = 3600)  

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 集成 Security、JWT 和 Redis 可以实现基于 Token 的权限认证和会话管理。 首先,需要在 pom.xml 文件中添加相应的依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 接下来,在 Spring Boot 的配置文件中添加 Redis 的配置和 JWT 的配置: ```yml spring: redis: host: localhost port: 6379 password: database: 0 jwt: secret: your_secret expiration: 86400 ``` 其中,jwt.secret 为 JWT 的密钥,jwt.expiration 为 Token 的有效期。 然后,需要实现一个 Security 的配置类,用于配置 Token 的认证和会话管理: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsServiceImpl userDetailsService; @Autowired private JwtAuthenticationEntryPoint unauthorizedHandler; @Bean public JwtAuthenticationFilter authenticationTokenFilterBean() throws Exception { return new JwtAuthenticationFilter(); } @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Override public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception { authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(HttpSecurity httpSecurity) throws Exception { httpSecurity .cors().and().csrf().disable() .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() .authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/**").permitAll() .antMatchers("/api/auth/**").permitAll() .anyRequest().authenticated(); // 添加 JWT filter httpSecurity.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class); } } ``` 其中,UserDetailsServiceImpl 是自定义的用户详情服务,JwtAuthenticationEntryPoint 是自定义的 Token 无效或过期的处理器,JwtAuthenticationFilter 是自定义的 Token 认证过滤器。 最后,需要实现一个 JWT 的工具类,用于生成 Token 和解析 Token: ```java @Component public class JwtTokenUtil { @Value("${jwt.secret}") private String secret; @Value("${jwt.expiration}") private Long expiration; public String generateToken(UserDetails userDetails) { Map<String, Object> claims = new HashMap<>(); return Jwts.builder() .setClaims(claims) .setSubject(userDetails.getUsername()) .setIssuedAt(new Date()) .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000)) .signWith(SignatureAlgorithm.HS512, secret) .compact(); } public String getUsernameFromToken(String token) { return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody().getSubject(); } public boolean validateToken(String token, UserDetails userDetails) { final String username = getUsernameFromToken(token); return username.equals(userDetails.getUsername()) && !isTokenExpired(token); } private Boolean isTokenExpired(String token) { final Date expiration = getExpirationDateFromToken(token); return expiration.before(new Date()); } private Date getExpirationDateFromToken(String token) { return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody().getExpiration(); } } ``` 在需要进行 Token 认证的控制器中,可以通过 @AuthenticationPrincipal 注解获取当前登录的用户信息: ```java @RestController @RequestMapping("/api") public class UserController { @Autowired private UserService userService; @Autowired private JwtTokenUtil jwtTokenUtil; @GetMapping("/user/me") public User getCurrentUser(@AuthenticationPrincipal UserDetails userDetails) { String username = userDetails.getUsername(); return userService.findByUsername(username); } @PostMapping("/auth/login") public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest) { Authentication authentication = authenticationManager.authenticate( new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()) ); SecurityContextHolder.getContext().setAuthentication(authentication); String token = jwtTokenUtil.generateToken(authentication.getPrincipal()); return ResponseEntity.ok(new JwtAuthenticationResponse(token)); } } ``` 以上就是 Spring Boot 集成 Security、JWT 和 Redis 的基本配置和使用方式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值