Spring Security 6.2.1默认登录表单无法禁用问题求助
Spring Security 6.2.1 + Spring Boot 3.2 自定义登录页无法禁用默认表单问题
使用Spring Security 6.2.1搭配Spring Boot 3.2开发Web应用,希望使用自定义登录页,但始终被重定向到默认登录表单,无法禁用默认表单。访问http://127.0.0.1:8080/mylogin时,期望跳转至自定义页面而非默认表单,已参考官方文档配置但问题依旧。
当前过滤器配置代码
@Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { try { http // ... .httpBasic(httpBasic -> httpBasic.disable()) .authorizeHttpRequests((authorizeExchange) -> authorizeExchange .requestMatchers("/mylogin").permitAll() .anyRequest().permitAll()) .csrf((csrf) -> csrf.disable()) .formLogin(form -> form.loginPage("/login").permitAll()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return http.build(); }
相关日志信息
2024-01-03 11:30:35.602 | DEBUG | parallel-1 | WebSessionServerRequestCache:83 | | Request added to WebSession: '/mylogin' 2024-01-03 11:30:35.603 | DEBUG | parallel-1 | DefaultServerRedirectStrategy:54 | | Redirecting to '/login' 2024-01-03 11:30:35.638 | DEBUG | http-nio-8080-exec-4 | OrServerWebExchangeMatcher:57 | | Trying to match using PathMatcherServerWebExchangeMatcher{pattern='/login', method=POST} 2024-01-03 11:30:35.639 | DEBUG | http-nio-8080-exec-4 | PathPatternParserServerWebExchangeMatcher:82 | | Request 'GET /login' doesn't match 'POST /login' 2024-01-03 11:30:35.639 | DEBUG | http-nio-8080-exec-4 | OrServerWebExchangeMatcher:62 | | No matches found 2024-01-03 11:30:35.639 | DEBUG | http-nio-8080-exec-4 | OrServerWebExchangeMatcher:57 | | Trying to match using PathMatcherServerWebExchangeMatcher{pattern='/login', method=GET} 2024-01-03 11:30:35.640 | DEBUG | http-nio-8080-exec-4 | PathPatternParserServerWebExchangeMatcher:100 | | Checking match of request : '/login'; against '/login' 2024-01-03 11:30:35.640 | DEBUG | http-nio-8080-exec-4 | OrServerWebExchangeMatcher:62 | | matched
问题分析与修复方案
从日志可见,请求/mylogin被重定向到/login,但你并未提供/login路径的自定义视图,因此Spring Security自动启用默认表单。同时当前配置存在两处关键问题:
- 登录页路径不匹配:配置中
formLogin指定loginPage("/login"),但你期望用/mylogin作为登录页,导致未认证请求被定向到不存在自定义视图的/login。 - 权限配置无效:
anyRequest().permitAll()允许所有请求跳过认证,破坏了Spring Security的认证逻辑,反而引发异常跳转。
修正后的配置代码
@Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .csrf(csrf -> csrf.disable()) .authorizeHttpRequests(auth -> auth // 允许无访问自定义登录页 .requestMatchers("/mylogin").permitAll() // 其余请求需认证 .anyRequest().authenticated() ) .formLogin(form -> form // 指定自定义登录页路径 .loginPage("/mylogin") // 指定登录请求提交路径(与表单action一致,默认同loginPage) .loginProcessingUrl("/mylogin") // 允许所有访问登录相关路径 .permitAll() ); return http.build(); }
额外注意事项
- 必须为
/mylogin路径创建控制器和视图,示例:@Controller public class LoginController { @GetMapping("/mylogin") public String showLoginPage() { return "login"; // 对应视图模板文件,如templates/login.html } } - 移除配置中的
try-catch块,避免吞掉配置异常导致无法排查问题。 - 不要设置
anyRequest().permitAll(),这会完全关闭认证校验,失去Spring Security的核心作用。
内容的提问来源于stack exchange,提问作者Totobond
相关产品推荐
相关产品推荐

