作者:ELEFTHERIA STEIN-KOUSATHANA
发表日期:2022年2月21日
在Spring Security 5.7.0-M2,我们弃用了 WebSecurityConfigurerAdapter
,因为我们鼓励用户转向使用基于组件的安全配置。
为了帮助大家熟悉这种新的配置风格,我们编制了一份常见用例表和推荐的新写法。
在下面的例子中,我们遵循最佳实践——使用Spring Security lambda领域专用语言(DSL)和 HttpSecurity#authorizeHttpRequests
方法来定义我们的授权规则。如果你对lambda领域专用语言(DSL)不熟悉,你可以在这篇博客了解它。如果你想知道为什么我们选择选择使用 HttpSecurity#authorizeHttpRequests
,你可以看这篇参考文档。
配置HttpSecurity
下面是一个使用 WebSecurityConfigurerAdapter
和HTTP Basic保护所有端点的示例配置:
往后,我们建议注册一个 SecurityFilterChain
bean来做这件事:
配置WebSecurity
WebSecurityCustomizer
是一个回调接口,可以用来定制 WebSecurity
。
下面是一个使用 WebSecurityConfigurerAdapter
忽略匹配 /ignore1
或 /ignore2
的请求的示例配置:
往后,我们建议注册一个 WebSecurityCustomizer
bean来做这件事:
LDAP认证
在Spring Security 5.7,我们引入了 EmbeddedLdapServerContextSourceFactoryBean
、 LdapBindAuthenticationManagerFactory
和 LdapPasswordComparisonAuthenticationManagerFactory
,这些类都可以用来创建一个嵌入式的LDAP服务器;并且我们还引入一个 AuthenticationManager
类,它可以用来执行LDAP认证。
下面是一个使用是一个使用绑定验证的示例配置,它使用了 WebSecurityConfugurerAdapter
创建嵌入式LDAP服务器并且使用 AuthenticationManager
执行LDAP认证(Below is an example configuration using WebSecurityConfigurerAdappter
the that creates an embedded LDAP server and an AuthenticationManager
that performs LDAP authentication using bingd authentication):
往后,我们建议使用新的LDAP类来做这件事:
JDBC认证
下面是一个示例配置,它在 WebSecurityConfigurerAdapter
内创建了一个使用默认模式初始化并且只有一个用户的内嵌 DataSource
:
推荐的做法是创建一个 JdbcUserDetailsManager
bean来做这件事:
注意:在这些例子中,我们为了可读性使用了 User.withDefaultPasswrdEncoder()
。这不适合生产项目,我们建议在生产项目中使用散列密码。请按照参考文档所说的用Spring Boot命令行工具来做。
内存内认证
下面是一个示例配置,它在 WebSecurityConfugurerAdapter
配置了一个只存有一个用户的内存内用户:
我们建议注册一个 InMemoryUserDetailsManager
bean来做这件事:
注意:在这些例子中,我们为了可读性使用了 User.withDefaultPasswrdEncoder()
。这不适合生产项目,我们建议在生产项目中使用散列密码。请按照参考文档所说的用Spring Boot命令行工具来做。
全局AuthenticationManager
要创建一个整个应用都可以使用的 AuthenticationManager
,只需要使用@Bean将 AuthenticationManager
注册为bean就可以了。
这种配置已经在上面的LDAP认证示例展示过了。
局部AuthenticationManager
下面是一个示例配置,它设置了一个自定义的 AuthenticationManager
:
访问局部AuthenticationManager
可以使用自定义领域专用语言(DSL)访问局部 AuthenticationManager
。这实际上是Spring Security内部实现 HttpSecurity.authorizeRequests()
等方法的方式。
然后,在构建 SecurityFilterchain
时可以应用自定义领域专用语言(DSL):
欢迎加入
Original: https://www.cnblogs.com/cnblog-user/p/16386942.html
Author: Halloworlds
Title: 【翻译】SpringSecurity抛弃了WebSecurityConfigurerAdapter
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/712900/
转载文章受原作者版权保护。转载请注明原作者出处!