spring-security - 在 Spring oauth2 中使用类 ResourceServerConfiguration.configure 中的 HttpSecurity.requestMatchers
问题描述
我一直在努力理解如何以及何时使用HttpSecurity.requestMatchers
. 虽然我使用HttpSecurity.requestMatchers
但我已经调用authorizeRequests
并antMatchers
指定安全规则。
我应该什么时候使用
http.requestMatchers()
.antMatchers("/secure/**","/patients/**","/patient/**", "/hello/**")
.and()
.authorizeRequests().antMatchers("/secure/**","/books/**","/book/**", "/hello/**")
.hasAnyRole("ADMIN","USER");
超过
http
.authorizeRequests().antMatchers("/secure/**","/books/**","/hello/**", "/hello/**")
.hasAnyRole("ADMIN","USER");
一个场景将帮助我理解HttpSecurity.requestMatchers
我确实研究了requestMatchers,但我仍然不清楚
解决方案
如果您需要HttpSecurity
在应用程序中配置多个,那么您通常会使用HttpSecurity.requestMatchers()
或替代(但类似)配置选项之一:
HttpSecurity.requestMatcher(RequestMatcher)
HttpSecurity.antMatcher(String)
HttpSecurity.mvcMatcher(String)
HttpSecurity.regexMatcher(String)
例如,如果您的应用程序有一组根植于基本路径的 API/api
和另一类用于根植于基本路径的应用程序管理部分的端点,/admin
那么您可以为您的应用程序定义 2x WebSecurityConfigurerAdapter
:
@EnableWebSecurity
public class SecurityConfig {
@Configuration
@Order(1)
public static class ApiWebSecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
http
.requestMatchers()
.antMatchers("/api/**")
.and()
.authorizeRequests()
.antMatchers("/api/endpoint1")
.hasRole("USER1");
}
}
@Configuration
public static class AdminWebSecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
http
.requestMatchers()
.antMatchers("/admin/**")
.and()
.authorizeRequests()
.antMatchers("/admin/endpoint1")
.hasRole("ADMIN1");
}
}
}
但是,如果您只提供 1x,则WebSecurityConfigurerAdapter
不需要配置HttpSecurity.requestMatchers()
(或任何替代方案),因为它会自动默认为HttpSecurity.requestMatcher(AnyRequestMatcher.INSTANCE)
. 所以对于这些配置情况,这就足够了:
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(...
}
}
希望这是有道理的?
推荐阅读
- jquery - 使用 jQuery 将图像适合表格单元格
- c++ - 我们可以在标准容器中使用 std::auto_ptr<> 吗?是的,但使用移动语义
- excel - 字符串值操作
- c# - 覆盖“公共”继承成员时无法更改访问修饰符
- javascript - 绑定滚动事件不会在角度指令中触发
- reactjs - 如何将参数传递给reactjs中的事件句柄
- ansible - 使用 Ansible 获取 VMware 虚拟机的 UUID
- neo4j - 有没有办法一起执行所有 3 个查询?
- c# - 如何通过 Socket C# 发送长字符串
- java - 如何使用 phantomjs 将多个 Web 元素传递到页面