在学习SpringCloud过程中看到以下一段关于OAuth2的代码,非常好奇为什么以"/oauth"开头的请求配置了两次拦截,一个requestMatchers(),一个authorizeRequests()
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class)
.requestMatchers()
.antMatchers("/oauth/**")
.and()
.authorizeRequests()
.antMatchers("/oauth/**").authenticated()
.and()
.csrf().disable();
}
查阅了相关资料,总结如下: 1.requestMatchers()
@Override
public void configure(HttpSecurity http) throws Exception {
http.
requestMatchers().antMatchers("/oauth/**") // 只有以/oauth开头的请求需要进行权限认证
.and()
.authorizeRequests().antMatchers("/**").authenticated(); // 其他接口都放行
}
另一种写法
@Override
public void configure(HttpSecurity http) throws Exception {
http.
requestMatchers().anyRequest() // requestMatchers().anyRequest()表示所有接口不进行认证
.and()
.authorizeRequests().antMatchers("/oauth/*").authenticated(); // 只拦截以/oauth开头的请求,并进行认证
}
综上两种写法,可以看出第一段中的代码是把以上两种写法合并了,目的就是只拦截以/oauth开头的请求,其他请求一律放行。
2.authorizeRequests()有以下几种常见的用法
// 所有接口都不拦截
http.authorizeRequests().antMatchers("/**").permitAll();
// 所有接口都会进行权限拦截
http.authorizeRequests().antMatchers("/**").authenticated();
// 只有以oauth开头的接口才进行权限认证,其他请求全部放行
http.authorizeRequests().antMatchers("/oauth/**").authenticated();
// 以/test开头的请求需要user角色才行,其他接口只要登陆过就能请求
http.authorizeRequests().antMatchers("/test/**").hasRole("user").antMatchers("/**").authenticated();
// 控制多个角色的时候.hasRole改为.hasAnyRole("user","admin")



