用过WebSecurityConfigurerAdapter的都知道,它对SpringSecurity非常重要,负责SpringSecurity的配置系统。但是这个类很快就会被废除,你没有看错,这个类在5.7版本中会被@Deprecated标记,以后会被移除。对此,网友大呼,“学不会学就会被抛弃”。既然快要弃用了,肯定要有过渡的方案或者新的玩法。胖哥早在2021年3月就写了一篇文章,把新玩法解释的清清楚楚。看过了,肯定学不会过时的技术。这里把整套备选方案再做一遍,不要学过时的技术。版本需要SpringSecurity5.4.x及以上版本。HttpSecurity新老方式对比老方式:@ConfigurationstaticclassSecurityConfigextendsWebSecurityConfigurerAdapter{@Overrideprotectedvoidconfigure(HttpSecurityhttp)throwsException{http.antMatcher("/**").authorizeRequests(authorize->authorize.anyRequestic()));}}新玩法:@BeanSecurityFilterChainfilterChain(HttpSecurityhttp)throwsException{returnhttp.antMatcher("/**").authorizeRequests(authorize->authorize.anyRequest().authenticated()).build();}原理看这篇文章。WebSecurity的新旧玩法对比使用WebSecurity.ignoring()忽略某些URL请求,这些请求会被SpringSecurity忽略,也就是说这些URL会受到CSRF、XSS、Clickjacking等攻击。以下示例仅供演示,请勿在生产环境中使用。你又学会了吗?旧方法:@ConfigurationpublicclassSecurityConfigurationextendsWebSecurityConfigurerAdapter{@Overridepublicvoidconfigure(WebSecurityweb){//仅用于演示web.ignoring().antMatchers("/ignore1","/ignore2");}}新方法:@ConfigurationpublicclassSecurityConfiguration{@BeanpublicWebSecurityCustomizerwebSecurityCustomizer(){//仅用于演示return(web)->web.ignoring().antMatchers("/ignore1","/ignore2");如果您需要忽略URL,请考虑通过HttpSecurity.authorizeHttpRequests实现permitAll。AuthenticationManager新老玩法对比AuthenticationManager的配置主要分为全局(Global)和局部(Local)。老玩意}}以上是WebSecurityConfigurerAdapter启用的本地配置。要启用全局配置,您需要覆盖其authenticationManagerBean()方法并将其标记为Bean:.authenticationManager实现:@ConfigurationpublicclassSecurityConfiguration{@BeanpublicSecurityFilterChainfilterChain(HttpSecurityhttp)throwsException{http.authorizeHttpRequests((authz)->authz.anyRequest().authenticated()).httpBasicer(wiicer)newCustomAuthenticationManager());}}全局配置摆脱了对WebSecurityConfigurerAdapter.authenticationManagerBean()方法的依赖,只需要定义一个AuthenticationManager类型的Bean:ry=newLdapBindAuthenticationManagerFactory(contextSource);factory.setUserDnPatterns("uid={0},ou=people");factory.setUserDetailsContextMapper(newPersonContextMapper());返回工厂.createAuthenticationManager();并注入SpringIoC修改AuthenticationManagerBuilder,数量没有限制,但是注意排序问题相关的思维导图:最后很多技术方案不是直接改的,会有一个改的过程,只要当你跟上变化时,实际上并没有变化。关注公众号:Felordcn获取更多资讯个人博客:https://felord.cn
