Spring Security配置-HttpSecurity与WebSecurity

时间:2019-05-31 04:57:04

标签: java spring-boot spring-security

我只需要了解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/**的请求而无需任何身份验证吗?

3 个答案:

答案 0 :(得分:3)

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)用于影响全局安全性的配置设置(忽略资源,设置调试模式,通过实现自定义防火墙定义拒绝请求)。例如,以下方法将导致以/ resources /开头的任何请求都被忽略,以进行身份​​验证。

答案 1 :(得分:1)

使用tage.initStyle(StageStyle.UNDECORATED); 并尝试HttpSecurity请求时。您的请求将被允许从Spring Security过滤链访问。这是昂贵的,因为还会有其他请求也要进入此过滤器链的请求,这些请求需要基于身份验证/授权来允许或禁止。

permitAll()

但是,当您使用时,对HttpSecurity.authorizeRequests().antMatchers("/**", "/resources/**").permitAll(); 的任何请求都将完全通过Spring Security筛选器链。这是安全的,因为您不需要进行任何身份验证/授权就可以查看图像或读取javascript文件。

resources

答案 2 :(得分:0)

configure(HttpSecurity):它允许为特定的HTTP请求配置基于Web的安全性。它用于基于选择匹配在资源级别上配置基于Web的安全性。

configure(WebSecurity):允许添加Spring Security应该忽略的RequestMatcher实例。