我只需要了解Spring Security Configuration中的内容。使用下面的示例...
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.httpBasic()
.and()
.authorizeRequests().antMatchers("/secret/**").authenticated()
.and()
.authorizeRequests().antMatchers("/**").permitAll();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**");
}
}
configure(WebSecurity web)
方法的目的是什么?我不能只在这行
/resources/**
的configure(HttpSecurity http)
方法中添加.authorizeRequests().antMatchers("/**", "/resources/**").permitAll();
它不应该一样工作,即允许所有对/resources/**
的请求都无需任何身份验证吗? 最佳答案
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();
}
上面的示例中的WebSecurity让Spring忽略/resources/**
和/publics/**
。因此,不考虑HttpSecurity中的.antMatchers("/publics/**").hasRole("USER")
。configure(HttpSecurity)
允许基于选择匹配在资源级别配置基于网络的安全性,例如下面的示例将以/admin/
开头的URL限制为具有ADMIN角色的用户,并声明需要成功进行身份验证的所有其他URL。configure(WebSecurity)
用于影响全局安全性的配置设置(忽略资源,设置 Debug模式,通过实现自定义防火墙定义拒绝请求)。例如,以下方法将导致出于身份验证目的而忽略以/resources/
开头的任何请求。让我们考虑下面的代码,我们可以使用这两种方法忽略antMatchers中提供的端点的身份验证。
@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/login", "/register", "/api/public/**");
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/login", "/register", "/api/public/**").permitAll()
.anyRequest().authenticated();
}
configure(WebSecurity web)
此方法中使用的端点会忽略Spring安全过滤器,安全功能(安全 header ,csrf保护等)也将被忽略,并且不会设置安全上下文,并且无法为跨站点脚本,XSS攻击,内容嗅探保护端点。configure(HttpSecurity http)
此方法中使用的端点忽略对antMatchers中使用的端点的身份验证,其他有效功能(例如安全 header ,CSRF保护等)将生效。