You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Security中and()与formLogin()废弃方法替换求助

修正Spring Security中and()和formLogin()废弃问题

在Spring Security 6+版本里,无参的and()和formLogin()方法已被废弃,需要改用基于Lambda的配置风格重构代码,以下是修正后的完整实现:

import org.springframework.security.config.Customizer;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(authz -> authz
            .requestMatchers("/registration**", "/js/**", "/css/**", "/img/**")
            .permitAll()
            .anyRequest()
            .authenticated()
        )
        .formLogin(form -> form
            .loginPage("/login")
            .permitAll()
        )
        .logout(logout -> logout
            .invalidateHttpSession(true)
            .clearAuthentication(true)
            .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
            .logoutSuccessUrl("/login?logout")
            .permitAll()
        )
        .httpBasic(Customizer.withDefaults());
    
    return http.build();
}

关键修改说明:

  • 移除所有and()方法:Spring Security 6推荐将授权、表单登录、登出等不同配置段作为HttpSecurity的独立方法调用,不再需要用and()链式连接
  • 替换无参formLogin():改用formLogin(form -> {...})的Lambda形式,在内部直接配置登录页和权限控制
  • 重构登出配置:将原分散的登出属性整合到logout(logout -> {...})的Lambda中,避免原代码中调用Customizer.withDefaults()后覆盖配置的问题

内容的提问来源于stack exchange,提问作者Arya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 08:12:12