谁能解释一下何时覆盖 configure(HttpSecurity)
、configure(WebSecurity)
和 configure(AuthenticationManagerBuilder)
?
最佳答案
configure(AuthenticationManagerBuilder) 用于通过允许轻松添加 AuthenticationProviders 来建立身份验证机制:例如下面定义了使用内置“用户”和“管理员”登录的内存身份验证。
public void configure(AuthenticationManagerBuilder auth) {
auth
.inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER")
.and()
.withUser("admin")
.password("password")
.roles("ADMIN","USER");
}
configure(HttpSecurity) 允许基于选择匹配在资源级别配置基于 Web 的安全性 - 例如下面的示例将对以/admin/开头的 URL 限制为具有 ADMIN 角色的用户,并声明任何其他 URL 都需要成功验证。
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
}
configure(WebSecurity) 用于影响全局安全的配置设置(忽略资源、设置 Debug模式、通过实现自定义防火墙定义拒绝请求)。例如,以下方法会导致任何以/resources/开头的请求被忽略以进行身份验证。
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/resources/**");
}
更多信息可以引用以下链接Spring Security Java Config Preview: Web Security
关于java - HttpSecurity、WebSecurity 和 AuthenticationManagerBuilder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22998731/