在 WebSecurity 中正确使用 WebSecurityConfigurerAdapter

2022-09-03 00:31:23

在我基于版本1.3.0.BUILD-SNAPSHOTSpring Boot应用程序中,我在.staticresources

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

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

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

这个例子是正确的吗?效果应该是什么?如何验证它是否有效(例如,向 ?我可以用什么很酷的东西?localhost:8080/somethingWebSecurity


答案 1

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

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

有关详细信息,请参阅 WebSecurity API 文档。

您可以根据需要拥有任意数量的受保护或不安全的 URL 模式。
使用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

WebSecurity方法的一般使用省略了Spring Security,并且Spring Security的任何功能都不可用。WebSecurity基于HttpSecurity
(在XML配置中,您可以编写以下内容:)。ignoring()<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();
}

在上面的例子中,WebSecurity让Spring忽略和。因此,在HttpSecurity中是未经考虑的。/resources/**/publics/**.antMatchers("/publics/**").hasRole("USER")

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


示例 2

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

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

答案 2

好吧,在你共享的代码中,如果你有静态文件,即.CSS/ JS等在一个名为static的文件夹中,那么你所有的静态资源都将添加到页面中,而如果你省略了

web.ignoring()
    .antMatchers("/static/**");

不会加载任何静态资源。

Spring Security非常强大,Spring有很好的文档,所以你应该去阅读它,充分欣赏/理解它。

这是一个链接