Spring Boot 3使用requestMatchers无法授权访问登录页的问题
解决Spring Boot 3.0(Spring Security 6)登录表单授权重定向循环问题
问题核心原因
Spring Security 6中requestMatchers的匹配逻辑是从上到下匹配,匹配到即停止执行后续规则,且需要明确放行登录流程中的所有必要路径(包括登录页、登录提交接口、静态资源等),否则会因登录请求被拦截触发重定向循环。
正确配置方案
替换原有SecurityFilterChain中的授权规则部分,调整匹配顺序并放行所有登录相关路径:
@Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { // 关闭XSS保护 http.headers().xssProtection().disable(); http.httpBasic().disable(); http.authorizeHttpRequests(auth -> auth // 优先放行登录页、登录提交接口、静态资源 .requestMatchers("/login.html", "/login", "/resources/**").permitAll() // 管理员路径需SUPERADMIN角色 .requestMatchers("/admin/**").hasRole("SUPERADMIN") // 内容路径需USER角色 .requestMatchers("/content/**").hasRole("USER") // 其余所有请求需USER角色认证 .anyRequest().hasRole("USER") ) .formLogin(form -> form .loginPage("/login.html") .usernameParameter("username") .passwordParameter("password") .successHandler(customLoginSuccessHandler) .failureHandler(customAuthenticationFailureHandle) ) .logout(logout -> logout .logoutSuccessUrl("/login.html") // 放行登出请求 .permitAll() ) .exceptionHandling(ex -> ex .accessDeniedHandler(accessDeniedHandler()) ) .rememberMe(remember -> remember .tokenRepository(persistentTokenRepository()) .tokenValiditySeconds(1209600) // 2周有效期 .alwaysRemember(true) .useSecureCookie(true) ) .csrf(csrf -> csrf // 忽略登录接口的CSRF校验(若表单未携带CSRF令牌) .ignoringRequestMatchers("/login") ); http.securityContext(securityContext -> securityContext.requireExplicitSave(true)); return http.build(); }
关键配置说明
- 匹配顺序优先级:将
permitAll规则放在最前面,确保登录相关路径不会被后续的认证规则拦截。 - 放行必要路径:
/login.html:自定义登录页路径/login:默认登录提交接口路径(若自定义了提交路径,需替换为实际路径并加入permitAll)/resources/**:静态资源路径,避免样式、脚本等被拦截
- 明确兜底规则:用
anyRequest().hasRole("USER")替代requestMatchers("/**").hasRole("USER"),语义更清晰,确保所有未匹配的请求都被覆盖。 - CSRF配置:若登录表单未携带CSRF令牌,需通过
csrf.ignoringRequestMatchers("/login")忽略该路径的CSRF校验,否则登录会失败。
内容的提问来源于stack exchange,提问作者Prospero
相关产品推荐
相关产品推荐

