Spring Security OAuth2登录:Token过期后重登方案求助
Token过期后自动重新登录实现方案
1. 调整过期Token过滤器逻辑
确保你的expiredTokenFilter在检测到Token过期时,抛出**AuthenticationCredentialsNotFoundException**(或自定义Token过期异常),而非直接返回错误响应。示例过滤器核心逻辑:
public class ExpiredTokenFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String token = extractTokenFromRequest(request); if (token != null && isTokenExpired(token)) { // Token过期时抛出认证凭证异常 throw new AuthenticationCredentialsNotFoundException("Token已过期,请重新登录"); } filterChain.doFilter(request, response); } // 从请求中提取Token的逻辑(示例从Header获取) private String extractTokenFromRequest(HttpServletRequest request) { return request.getHeader("Authorization"); } // Token过期判断逻辑(替换为你的真实校验逻辑) private boolean isTokenExpired(String token) { // 示例返回true,实际需解析Token并判断过期时间 return true; } }
2. 配置异常处理引导重新登录
修改Spring Security配置中的异常处理逻辑,捕获Token过期异常并跳转至OAuth2登录页面:
@Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .requestMatchers(SecurityUtils::isFrameworkInternalRequest).permitAll() .accessDecisionManager(accessDecisionManager()) .and() .addFilterAfter(expiredTokenFilter, BasicAuthenticationFilter.class); http.exceptionHandling() .accessDeniedHandler(new CustomAccessDeniedHandler()) // 处理Token过期等认证凭证异常 .authenticationEntryPoint((request, response, authException) -> { if (authException instanceof AuthenticationCredentialsNotFoundException) { // 替换为你的OAuth2提供商ID(如google、github) response.sendRedirect("/oauth2/authorization/your-provider-id"); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage()); } }) .and() .oauth2Login(oauth2Login -> oauth2Login .successHandler(new VaadinSavedRequestAwareAuthenticationSuccessHandler()) .userInfoEndpoint(userInfoEndpointConfig -> userInfoEndpointConfig.oidcUserService(oidcUserService))) .logout(logout -> logout .logoutSuccessHandler(logoutSuccessHandler()) .logoutRequestMatcher(new AntPathRequestMatcher("/logout", "GET")) ); super.configure(http); }
3. 关键说明
- 替换
your-provider-id为你实际使用的OAuth2服务商标识 - 若使用自定义Token过期异常,需在
authenticationEntryPoint中对应判断异常类型 VaadinSavedRequestAwareAuthenticationSuccessHandler会自动保存用户原访问页面,登录成功后自动跳转回去,无需额外配置
内容的提问来源于stack exchange,提问作者Алексей Шерстобитов
相关产品推荐
相关产品推荐

