简介
资源服务器会对所有的请求进行拦截认证,当然除了oauth相关的请求之外。同时会创建一个拦截器OAuth2AuthenticationProcessingFilter,该拦截器会对请求头Authorization中的值进行相关验证。
使用方式:
1、添加注解@EnableResourceServer
2、继承ResourceServerConfigurerAdapter
@Configuration
@EnableResourceServer
public static class ResourceServerConfigurer extends ResourceServerConfigurerAdapter {
}
@EnableResourceServer导入了ResourceServerConfiguration配置类,该配置类继承了WebSecurityConfigurerAdapter,拥有了http security的相关能力。
@Configuration
public class ResourceServerConfiguration extends WebSecurityConfigurerAdapter implements Ordered {
......
//请求匹配,对oauth相关请求放行,其他请求拦截
private static class NotOAuthRequestMatcher implements RequestMatcher {
private FrameworkEndpointHandlerMapping mapping;
public NotOAuthRequestMatcher(FrameworkEndpointHandlerMapping mapping) {
this.mapping = mapping;
}
@Override
public boolean matches(HttpServletRequest request) {
String requestPath = getRequestPath(request);
for (String path : mapping.getPaths()) {
if (requestPath.startsWith(mapping.getPath(path))) {
return false;
}
}
return true;
}
private String getRequestPath(HttpServletRequest request) {
String url = request.getServletPath();
if (request.getPathInfo() != null) {
url += request.getPathInfo();
}
return url;
}
}
@Override
protected void configure(HttpSecurity http) throws Exception {
//资源服务可配置类,添加了OAuth2AuthenticationProcessingFilter过滤器,对请求头Authorization进行验证
ResourceServerSecurityConfigurer resources = new ResourceServerSecurityConfigurer();
ResourceServerTokenServices services = resolveTokenServices();
if (services != null) {
resources.tokenServices(services);
}
else {
if (tokenStore != null) {
resources.tokenStore(tokenStore);
}
else if (endpoints != null) {
resources.tokenStore(endpoints.getEndpointsConfigurer().getTokenStore());
}
}
if (eventPublisher != null) {
resources.eventPublisher(eventPublisher);
}
for (ResourceServerConfigurer configurer : configurers) {
configurer.configure(resources);
}
// @formatter:off
http.authenticationProvider(new AnonymousAuthenticationProvider("default"))
// N.B. exceptionHandling is duplicated in resources.configure() so that
// it works
.exceptionHandling()
.accessDeniedHandler(resources.getAccessDeniedHandler()).and()//访问拒绝处理类
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.csrf().disable();
// @formatter:on
http.apply(resources);
if (endpoints != null) {
// Assume we are in an Authorization Server
http.requestMatcher(new NotOAuthRequestMatcher(endpoints.oauth2EndpointHandlerMapping()));
}
for (ResourceServerConfigurer configurer : configurers) {
// Delegates can add authorizeRequests() here
configurer.configure(http);
}
if (configurers.isEmpty()) {
// Add anyRequest() last as a fall back. Spring Security would
// replace an existing anyRequest() matcher with this one, so to
// avoid that we only add it if the user hasn't configured anything.
http.authorizeRequests().anyRequest().authenticated();
}
}
......
}
附流程图