spring-boot - 了解 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/**") 不匹配?
解决方案
的目的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/**"
它不是任何请求匹配器的一部分。
推荐阅读
- arrays - 在数组过滤器中添加两个条件
- javascript - AngularJS中从对象到ng-repeat的绑定指令
- azure - Powershell - 无需关闭应用程序即可设置环境变量
- reactjs - React JS ref(useRef):包含不是函数
- python - 使用 Python 在 Laravel 中使用 Symfony 进程时出错
- javascript - React Navigation——在一个屏幕上使用两个导航器
- http - HTTP 请求和响应中的“连接:关闭”标头
- ckeditor5 - CKEditor 5 内联小部件 -> 在之前添加空格
- java - 如何在java中输入长号码并输出电话号码?
- tensorflow - 如何在 conda 环境中安装旧版本的 CUDA?