SpringBoot3中SpringSecurity认证异常:/user路径需免登访问
解决Spring Boot3中Spring Security路径放行问题
核心配置修改
在Spring Boot3对应的Spring Security 6版本中,要让/user路径允许所有人无需认证访问,需在SecurityFilterChain配置中明确设置放行规则:
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; @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth // 放行/user路径,允许所有请求访问 .requestMatchers("/user").permitAll() // 其余所有路径需认证后访问 .anyRequest().authenticated() ) // 保留默认登录页配置(若不需要可直接移除该段) .formLogin(form -> form.permitAll()); return http.build(); } }
关键注意事项
- 必须使用
requestMatchers而非旧版的antMatchers(Spring Security 6中antMatchers已标记为过时) - 放行规则要写在
anyRequest().authenticated()之前,否则会被全局认证规则覆盖 - 若有静态资源(如CSS、JS文件)需要放行,可追加到
requestMatchers中,示例:requestMatchers("/user", "/css/**", "/js/**").permitAll()
控制器代码验证
确保你的控制器映射路径正确,示例:
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class UserController { @GetMapping("/user") public String userHome() { // 返回你的首页视图名称,比如"index" return "index"; } }
问题排查
如果配置后仍跳转到登录页,检查以下几点:
- 配置类是否被Spring Boot扫描到(确保配置类所在包在主启动类的同级或子级目录)
- 是否存在多个Security配置类导致规则冲突
- 路径拼写是否正确(Spring Security路径匹配默认区分大小写)
内容的提问来源于stack exchange,提问作者Mama
相关产品推荐
相关产品推荐

