Spring Security添加自定义认证过滤器后/login返回404,默认登录页消失如何解决
问题根因
- 调用
formLogin().loginPage("/login")后,Spring Security会判定你需要自定义登录页,不再自动生成内置默认登录页,这是/login返回404的核心原因。 - 配置
anyRequest().permitAll()导致所有请求直接放行,不会触发认证流程,自定义过滤器自然不会执行。 - 直接使用
addFilter添加自定义认证过滤器,没有替换默认的UsernamePasswordAuthenticationFilter,过滤器位置不对无法拦截登录请求。 - 依赖存在版本冲突,同时引入
spring-boot-starter-security和独立版本的spring-security-config,可能引发兼容问题。
解决方案
1. 清理依赖
删除gradle中单独引入的spring-security-config依赖,spring-boot-starter-security已经包含对应版本的配置模块,避免版本冲突:
implementation 'org.springframework.boot:spring-boot-starter-web' implementation group: 'com.auth0', name: 'java-jwt', version: '3.18.1' implementation 'org.springframework.boot:spring-boot-starter-security' implementation 'org.springframework.security:spring-security-test' implementation 'org.springframework.boot:spring-boot-starter-validation'
2. 修改安全配置
调整HttpSecurity配置逻辑,恢复默认登录页、修正授权规则、正确注册自定义过滤器:
@Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() .authorizeRequests() // 放开注册、登录相关路径的权限 .antMatchers("/register","/login").permitAll() // 其余请求需要认证 .anyRequest().authenticated() .and() .sessionManagement().sessionCreationPolicy(STATELESS) .and() // 只写formLogin()即可,不要加loginPage配置,这样才会生成默认登录页 .formLogin() .and() // 用addFilterAt替换默认的UsernamePasswordAuthenticationFilter .addFilterAt(new CustomAuthenticationFilter(authenticationManagerBean()), UsernamePasswordAuthenticationFilter.class); }
3. 可选:自定义过滤器登录路径
如果需要修改自定义过滤器拦截的登录请求路径,可以在过滤器构造方法中显式指定:
public CustomAuthenticationFilter(AuthenticationManager authenticationManager) { this.authenticationManager = authenticationManager; // 示例:修改为拦截POST /auth/login请求,不填则默认拦截POST /login setFilterProcessesUrl("/auth/login"); }
验证效果
启动服务后:
- GET请求
/login可正常访问Spring Security默认登录页 - 提交用户名密码登录时会触发自定义过滤器的
attemptAuthentication方法 - 认证成功后会返回你定义的JWT token结构
内容的提问来源于stack exchange,提问作者Stephen Carroll
相关产品推荐
相关产品推荐

