能否有人解释一下何时需要覆盖
configure(HttpSecurity)
、configure(WebSecurity)
和 configure(AuthenticationManagerBuilder)
方法?configure(HttpSecurity)
、configure(WebSecurity)
和 configure(AuthenticationManagerBuilder)
方法?configure(AuthenticationManagerBuilder) 用于建立身份验证机制,允许轻松添加 AuthenticationProviders。例如,以下内容定义了具有内置 'user' 和 'admin' 登录的内存身份验证。
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) 用于配置影响全局安全性的设置(忽略资源,设置调试模式,通过实现自定义防火墙定义拒绝请求)。例如,以下方法将导致任何以 /resources/ 开头的请求被忽略以进行身份验证。
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/resources/**");
}
您可以参考以下链接获取更多信息Spring Security Java Config Preview: Web Security
WebSecurity的常规用法中,使用ignoring()
方法会忽略Spring Security,因此Spring Security的任何功能都将不可用。
WebSecurity是基于HttpSecurity的。
@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/resources/**")
.antMatchers("/publics/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/publics/**").hasRole("USER") // no effect
.anyRequest().authenticated();
}
/resources/**
和 /publics/**
。因此,在 HttpSecurity 中的 .antMatchers("/publics/**").hasRole("USER")
将被忽略。
这将完全从安全过滤器链中省略请求模式。请注意,与此路径匹配的任何内容都将不会应用身份验证或授权服务,并且可以自由访问。
configure(HttpSecurity)
允许基于选择匹配对基于 Web 的安全性进行资源级别的配置 - 例如,以下示例将以 /admin/
开头的 URL 限制为具有ADMIN角色的用户,并声明需要成功认证任何其他 URL。
configure(WebSecurity)
用于影响全局安全的配置设置(忽略资源、设置调试模式、通过实现自定义防火墙定义来拒绝请求)。例如,以下方法将导致以 /resources/
开头的任何请求在身份验证方面被忽略。AuthenticationManagerBuilder
extends AbstractConfiguredSecurityBuilder<AuthenticationManager,AuthenticationManagerBuilder>
implements ProviderManagerBuilder<AuthenticationManagerBuilder>
SecurityBuilder用于创建AuthenticationManager
。它允许轻松地构建内存身份验证、LDAP身份验证、基于JDBC的身份验证,添加UserDetailsService和AuthenticationProvider
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
auth.userDetailsService(customUserDetailService).passwordEncoder(new BCryptPasswordEncoder());
}