springboot + security 自定义session过期处理方式

本文探讨了在SpringBoot集成Security时,如何处理Session过期的问题。默认的Session过期策略可能会导致不理想的结果,因此需要自定义策略。通过重写`onExpiredSessionDetected`方法并在`SessionManagementConfigurer`中配置,可以实现期望的Session过期行为。特别注意设置contentType以避免编码问题,否则可能导致中文乱码。
摘要由CSDN通过智能技术生成

security校验session校验是在ConcurrentSessionFilter,在doFilter方法里可以看到如果session过期会执行方法

this.doLogout(request, response);
this.sessionInformationExpiredStrategy.onExpiredSessionDetected(new SessionInformationExpiredEvent(info, request, response));

先做退出操作,在执行session过期策略,这个策略的初始化是在SessionManagementConfigurer.getExpiredSessionStrategy

SessionInformationExpiredStrategy getExpiredSessionStrategy() {
    if(this.expiredSessionStrategy != null) {
      return this.expiredSessionStrategy;
    } else if(this.expiredUrl == null) {
      return null;
    } else {
      if(this.expiredSessionStrategy == null) {
        this.expiredSessionStrategy = new SimpleRedirectSessionInformationExpiredStrategy(this.expiredUrl);
      }

      return this.expiredSessionStrategy;
    }
  }

所以如果你没有设置默认的策略和expiredU

好的,下面是 Spring Boot 后端和 Vue.js 前端的示例代码和步骤。 1. 在 Spring Boot 后端,我们可以使用 Spring Security 框架来实现基于 token 的认证和授权。 首先,在 pom.xml 文件中添加 Spring Security 的依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 其次,我们需要创建一个类来实现 Spring Security 的配置,例如: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Autowired private JwtAuthenticationEntryPoint unauthorizedHandler; @Bean public JwtAuthenticationFilter authenticationTokenFilterBean() throws Exception { return new JwtAuthenticationFilter(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(HttpSecurity http) throws Exception { http .cors().and().csrf().disable() .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() .authorizeRequests() .antMatchers("/api/auth/**").permitAll() .anyRequest().authenticated(); // 添加 JWT token 过滤器 http.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class); } } ``` 在上面的代码中,我们配置了 Spring Security 的一些基本参数,例如:使用 BCryptPasswordEncoder 进行密码加密,实现 UserDetailsService 接口来加载用户信息,配置 JWT token 过滤器等。 2. 在用户登录成功后,生成一个 token 并返回给前端。 在 Spring Boot 后端,我们可以使用 JWT token 来实现认证和授权。在用户登录成功后,我们需要生成一个 JWT token 并返回给前端,例如: ```java // 生成 JWT token String token = Jwts.builder() .setSubject(user.getUsername()) .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME)) .signWith(SignatureAlgorithm.HS512, SECRET) .compact(); // 将 token 返回给前端 response.addHeader(HEADER_STRING, TOKEN_PREFIX + token); ``` 在上面的代码中,我们使用 Jwts 类创建一个 JWT token,设置 token 的过期时间和签名算法,并将 token 添加到响应头中返回给前端。其中,HEADER_STRING 和 TOKEN_PREFIX 是我们自定义的常量。 3. 在前端,我们需要在请求头中添加 Authorization 字段,值为 "Bearer " + token。 在 Vue.js 前端,我们可以使用 axios 库来发送 HTTP 请求,并在请求头中添加 Authorization 字段。 首先,我们需要在 main.js 文件中设置 axios 的默认配置,例如: ```javascript import axios from 'axios' axios.defaults.baseURL = 'http://localhost:8080/api' axios.defaults.headers.common['Content-Type'] = 'application/json' // 在请求头中添加 Authorization 字段 axios.interceptors.request.use( config => { const token = localStorage.getItem('token') if (token) { config.headers.common['Authorization'] = 'Bearer ' + token } return config }, error => { return Promise.reject(error) } ) ``` 在上面的代码中,我们设置了 axios 的默认请求 URL 和请求头的 Content-Type。并在 axios 的请求拦截器中,判断本地存储中是否有 token,如果有,则将 token 添加到请求头的 Authorization 字段中。 4. 在后端,我们需要从请求头中解析出 token,然后使用 JWT token 进行验证和授权。 在 Spring Boot 后端,我们需要从请求头中解析出 Authorization 字段,然后使用 JWT token 进行验证和授权。 例如,在 JwtAuthenticationFilter 类中,我们可以重写 doFilterInternal 方法,从请求头中解析出 token,并将 token 传递给 JwtTokenUtil 类进行验证和授权,例如: ```java @Component public class JwtAuthenticationFilter extends OncePerRequestFilter { @Autowired private JwtTokenUtil jwtTokenUtil; @Autowired private UserDetailsService userDetailsService; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { String header = request.getHeader(HEADER_STRING); String username = null; String authToken = null; if (header != null && header.startsWith(TOKEN_PREFIX)) { authToken = header.replace(TOKEN_PREFIX, ""); try { username = jwtTokenUtil.getUsernameFromToken(authToken); } catch (IllegalArgumentException e) { logger.error("an error occurred during getting username from token", e); } catch (ExpiredJwtException e) { logger.warn("the token is expired and not valid anymore", e); } } else { logger.warn("couldn't find bearer string, will ignore the header"); } if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { UserDetails userDetails = userDetailsService.loadUserByUsername(username); if (jwtTokenUtil.validateToken(authToken, userDetails)) { UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); logger.info("authenticated user " + username + ", setting security context"); SecurityContextHolder.getContext().setAuthentication(authentication); } } chain.doFilter(request, response); } } ``` 在上面的代码中,我们首先从请求头中解析出 Authorization 字段,然后使用 JwtTokenUtil 类的 getUsernameFromToken 方法解析出 token 中的用户名。接着,我们使用 UserDetailsService 接口加载用户信息,并使用 JwtTokenUtil 类的 validateToken 方法进行 token 的验证和授权。最后,我们将用户信息设置到 Spring Security 的上下文中,以便后续的请求可以进行访问控制。 至此,我们就完成了 Spring Boot 后端和 Vue.js 前端如何在登录后请求头上加上 token 的示例代码和步骤。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值