我试图了解RequestMatcher,AntMatcher等的工作方式。我阅读了一些帖子并了解了基础知识。其实我有这个简单的基本配置:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.requestMatchers() //1
.antMatchers("/login", "/oauth/authorize") //2
.and() //3
.authorizeRequests() //4
.anyRequest() //5
.authenticated() //6;
我真的不理解第1,2和3点。根据我的理解,这意味着/login
和/oauth/authorize
的请求已映射,应该是授权的请求。所有其他请求都需要验证。
端点/user/me
的意思,我必须通过身份验证,因为它受第5点和第6点的约束?对此端点的呼叫对我有用。
在我的其他配置中,我尝试另一种方法:
@Override
protected void configure(HttpSecurity http) throws Exception { // @formatter:off
http
.authorizeRequests() //1
.antMatchers("/login", "/oauth/authorize", "/img/**").permitAll() //2
.anyRequest() //3
.authenticated() //4
从我的角度来看,这应该与第一个配置具有相同的逻辑。但是实际上端点/user/me
不再可访问。
我非常感谢您提供澄清
您的第一个配置。requestMtchers()// 1
@Override
protected void configure(HttpSecurity http) throws Exception {
http.requestMatchers() //1
.antMatchers("/login", "/oauth/authorize") //2
.and() //3
.authorizeRequests() //4
.anyRequest() //5
.authenticated() //6;
让我解释一下您的[[.authorizeRequests()
// 4
.authorizeRequests()
这是一个通配符(就像过滤器允许每个请求一样)HttpSecurity配置将仅考虑具有这些模式的请求在这里你可以说http.authorizeRequests()
//is nothing but equals to
http.antMatcher("/**").authorizeRequests();
//and also equals to
http.requestMatchers()
.antMatchers("/**")
.and()
.authorizeRequests()
如果您进行如下配置
http.antMatcher("/api/**").authorizeRequests();
仅当传入请求uri与配置的antmatcher(.hasRole()
)匹配时,才会咨询其余配置(.authenticated()
和/api/**
)考虑您需要配置多个URL(不同模式),那么您不能仅使用一个antMatcher。您需要多个,然后应使用requestMatcher,如下所示
http.requestMatchers() .antMatchers("/api/**", "employee/**", "/customer/**") .and() .authorizeRequests()
用于配置。antMatchers()// 2
RequestMatcherConfigurer
的.requestMatchers()
返回类型或者也用于配置ExpressionInterceptUrlRegistry
的.authorizeRequests()
返回类型。and()// 3
返回HttpSecurity进行进一步的自定义。anyRequest()// 5
创建RequestMatcher之后链接的对象所有请求都与配置的请求匹配器模式匹配
。authenticated()// 6
下面的配置是自我说明.antMatchers("/app/admin/**").hasRole("ADMIN")
//or
.antMatchers("/app/admin/**").hasAnyRole("ADMIN", "USER")
//or
.antMatchers("/app/admin/**").authenticated()
//or
.antMatchers("/app/admin/**").permitAll()
以上信息中有很多事情需要分析。如果您仍然有任何疑问,可以用相关的疑问来更新您的问题。