首页 > 解决方案 > 了解 spring-security 上的 requestMatchers()

问题描述

我正在研究一些弹簧安全代码。我想了解我在互联网 1上找到的这个例子:

http.requestMatchers()
        .antMatchers("/management/**") // (1)
        .and()
        .authorizeRequests() // (2)
        .antMatchers("/management/health")
        .permitAll()
        .antMatchers("/management/info")
        .permitAll()
        .antMatchers("/management/**")
        .hasRole("ACTUATOR")
        .anyRequest().permitAll()
        .and()
        .httpBasic(); (3)

}

我无法理解这个配置,为什么这个代码:

http.requestMatchers()
        .antMatchers("/management/**")
        .and() 

在 .authorizeRequests() 之前?(1)

这意味着什么?

你能解释一下这个例子吗?

2:第二种情况,有什么区别?

http.requestMatchers().antMatchers("/rest2/**")
.and()
.authorizeRequests()
.antMatchers("/rest/v1/test/hello").permitAll()
.antMatchers("/rest/v1/test/**").denyAll()
.and()
.requestMatchers().antMatchers("/rest/**")
.and()
.authorizeRequests()
.antMatchers("/rest/v1/test/hello").permitAll();

使用 requestMatchers() 有什么影响?

如果我向 "/rest/v1/test/hello2" 发送请求,我收到 401 为什么如果拒绝请求的规则与 antMatchers("/rest2/**") 不匹配?

标签: spring-bootspring-security

解决方案


的目的requestMatchers()是指定 spring 安全配置将应用于哪些请求。

例如,如果您有 2 个端点"/public""/private"并且您只想将安全性(特别是 csrf 保护)应用于"/private",那么您可以添加以下配置:

http
    .requestMatchers()
        .antMatchers("/private/**")
        .and()
    .csrf();

然后,如果你 POST 给你,"/private"你会得到一个 403 响应。
但是如果你 POST 给你,"/public"你会得到 200,因为没有应用任何安全措施。

这与authorizeRequests指示该端点所需的访问类型不同,与是否完全应用安全性相反。

在您提到的示例 1 中

http
    .requestMatchers()
        .antMatchers("/management/**")
        .and() 
        ...

安全配置仅适用于"/management/**",因此如果您向 提出请求"/foo",它将不受保护。

在您提到的示例 2 中,

http
    .requestMatchers()
        .antMatchers("/rest2/**")
        .and()
    .authorizeRequests()
        .antMatchers("/rest/v1/test/hello").permitAll()
        .antMatchers("/rest/v1/test/**").denyAll()
        .and()
    .requestMatchers()
        .antMatchers("/rest/**")
        .and()
    .authorizeRequests()
        .antMatchers("/rest/v1/test/hello").permitAll();

"/rest/v1/test/hello2"使用 401 响应的原因是"/rest/**"在请求匹配器中,因此您的安全规则.antMatchers("/rest/v1/test/hello").permitAll()将适用。
如果您要向 发出请求"/rest3/v1/test/hello2",那么它会以 200 响应,因为"/rest3/**"它不是任何请求匹配器的一部分。


推荐阅读