在WebSecurityConfigurerAdapter中正确使用WebSecurity

Jea*_*ean 12 java security spring spring-boot

在基于版本1.3.0.BUILD-SNAPSHOT的Spring Boot应用程序中,我在下面的文件夹中有静态资源(images,css,js).staticresources

我看到一些与安全配置相关的示例,如下所示:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(final WebSecurity web) throws Exception {
        web.ignoring()
           .antMatchers("/static/**");
    }
}
Run Code Online (Sandbox Code Playgroud)

这个例子是否正确?应该是什么影响?如何验证它是否有效(例如,请求localhost:8080/something?我可以做些什么很酷的事情WebSecurity

sve*_*tek 22

您的示例意味着Spring(Web)安全性忽略了与您定义的表达式匹配的Url-Pattern ("/static/**").安全性会跳过此Url,因此不受保护.

允许添加Spring Security应忽略的RequestMatcher实例.Spring Security提供的Web Security(包括SecurityContext)将无法在匹配的HttpServletRequest上使用.通常,注册的请求应该只是静态资源的请求.对于动态请求,请考虑将请求映射为允许所有用户.

请参阅:http://docs.spring.io/autorepo/docs/spring-security/4.0.0.RELEASE/apidocs/org/springframework/security/config/annotation/web/builders/WebSecurity.html

您可以拥有尽可能多的Url-Pattern安全或不安全.使用Spring Security,您可以为应用程序的Web层提供身份验证和访问控制功能.您还可以停止具有指定角色的用户访问部分Url等等...请查看此处:http://docs.spring.io/spring-security/site/docs/current/reference/html/

订购Url模式的优先级

将指定的模式与传入请求进行匹配时,匹配将按声明元素的顺序完成.因此,最具体的匹配模式应首先出现,最常见的应该是最后的.

http.authorizeRequests()方法有多个子节点,每个匹配器按其声明的顺序进行考虑.

模式始终按照定义的顺序进行评估.因此,重要的是在列表中定义的更具体的模式比不太具体的模式更高.

看看:http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#filter-security-interceptor

示例1
Generell使用WebSecurity ignoring()方法省略了Spring Security,并且Spring Security的所有功能都不可用.WebSecurity基于HttpSecurity.在Xml-Configuration中,您可以编写<http pattern="/resources/**" security="none"/>.

@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();
}
Run Code Online (Sandbox Code Playgroud)

WebSecurity在上面的例子中,让春忽略/resources/**/publics/**.因此.antMatchers("/publics/**").hasRole("USER"),HttpSecurity中没有被考虑.

这将完全省略安全过滤器链中的请求模式.请注意,与此路径匹配的任何内容都将不会应用任何身份验证或授权服务,并且可以自由访问.

示例2
始终按顺序评估模式.以下匹配无效,因为第一个匹配每个请求,并且永远不会应用第二个匹配:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
        .antMatchers("/**").hasRole("USER")
        .antMatchers("/admin/**").hasRole("ADMIN"):
}
Run Code Online (Sandbox Code Playgroud)