jav*_*Try 8 spring-security spring-boot
我正在研究一些弹簧安全代码。我想了解我在互联网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)
Run Code Online (Sandbox Code Playgroud)
}
我无法理解这个配置,为什么这个代码:
http.requestMatchers()
.antMatchers("/management/**")
.and()
Run Code Online (Sandbox Code Playgroud)
在 .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();
Run Code Online (Sandbox Code Playgroud)
使用 requestMatchers() 有什么影响?
如果我向 "/rest/v1/test/hello2" 发送请求,我会收到 401 为什么拒绝请求的规则与 antMatchers("/rest2/**") 不匹配?
Ele*_*ana 14
的目的requestMatchers()是指定 spring 安全配置将应用于哪些请求。
例如,如果您有 2 个端点"/public","/private"并且您只想将安全性(特别是 csrf 保护)应用于"/private",那么您可以添加以下配置:
http
.requestMatchers()
.antMatchers("/private/**")
.and()
.csrf();
Run Code Online (Sandbox Code Playgroud)
然后,如果您 POST 到"/private"您将收到 403 响应。
但是如果你 POST 到"/public"你会得到 200,因为没有应用安全。
这与authorizeRequestswhich 指示该端点所需的访问类型是分开的,而不是完全应用安全性。
在您提到的示例 1 中
http
.requestMatchers()
.antMatchers("/management/**")
.and()
...
Run Code Online (Sandbox Code Playgroud)
安全配置仅适用于"/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();
Run Code Online (Sandbox Code Playgroud)
"/rest/v1/test/hello2"以 401 响应的原因是因为"/rest/**"在请求匹配器中,因此您的安全规则.antMatchers("/rest/v1/test/hello").permitAll()将适用。
如果您要向 发出请求"/rest3/v1/test/hello2",那么它将以 200 响应,因为"/rest3/**"它不是任何请求匹配器的一部分。
non*_*oat 13
WebSecurityConfigurerAdapter已被删除,Spring Security 5.5 引入了一种使用SecurityFilterChain接口配置安全性的新方法 - HttpSecurity 构建器 API 已被弃用。
例如,要允许请求/public/以及进一步的一切,同时保留 ant-pattern 注释,请使用:
@Bean
public SecurityFilterChain configure(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((requests) -> requests
.requestMatchers(new AntPathRequestMatcher("/public/**")).permitAll()
.anyRequest().authenticated()) //other URLs are only allowed authenticated users.
.httpBasic();
return http.build();
}
Run Code Online (Sandbox Code Playgroud)
“经过身份验证的用户”的定义可以使用JwtTokenFilter扩展 a来指定OncePerRequestFilter(例如)。
| 归档时间: |
|
| 查看次数: |
10077 次 |
| 最近记录: |