Spring Boot Security登录后重定向至错误URL问题排查
Spring Boot Security登录后重定向异常解决方案
问题根源
HttpSessionRequestCache默认会缓存所有未授权的请求,哪怕是你已经通过permitAll()放行的静态资源。当访问/categories被跳转到登录页后,登录页加载时请求的/js/demo/chart-pie-demo.js这类静态资源,会覆盖掉最初缓存的/categories记录,导致登录后错误重定向到静态资源路径。
解决方案
自定义RequestCache,过滤掉静态资源请求,只缓存需要保护的业务请求:
1. 实现自定义RequestCache类
import org.springframework.security.web.savedrequest.HttpSessionRequestCache; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CustomRequestCache extends HttpSessionRequestCache { @Override public void saveRequest(HttpServletRequest request, HttpServletResponse response) { // 排除所有已放行的静态资源路径,根据实际情况调整前缀 String uri = request.getRequestURI(); if (!uri.startsWith("/css/") && !uri.startsWith("/js/")) { super.saveRequest(request, response); } } }
2. 在SecurityConfig中配置使用自定义缓存
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.savedrequest.RequestCache; @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public RequestCache customRequestCache() { return new CustomRequestCache(); } @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth .requestMatchers("/css/**", "/js/**", "/login", "/register").permitAll() .anyRequest().authenticated() ) .formLogin(form -> form .loginPage("/login") .permitAll() ) // 替换默认请求缓存为自定义实现 .requestCache(cache -> cache.requestCache(customRequestCache())); return http.build(); } }
注意事项
如果项目还有其他静态资源前缀(比如/img/、/fonts/),记得在CustomRequestCache的判断逻辑里添加对应的排除规则,确保所有已放行的静态资源请求都不会覆盖原有的业务请求缓存记录。
内容的提问来源于stack exchange,提问作者milanHrabos
相关产品推荐
相关产品推荐

