ResourceServerConfigurerAdapter (资源服务器配置)
内部关联了ResourceServerSecurityConfigurer 和 HttpSecurity。前者与资源安全配置相关,后者与http安全配置相关
/**
* ResourceServerSecurityConfigurer主要配置以下几方面:
* tokenServices:ResourceServerTokenServices 类的实例,用来实现令牌访问服务,如果资源服务和授权服务不在一块,就需要通过RemoteTokenServices来访问令牌
* tokenStore:TokenStore类的实例,定义令牌的访问方式
* resourceId:这个资源服务的ID
* 其他的拓展属性例如 tokenExtractor 令牌提取器用来提取请求中的令牌。
*/
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
//resourceId 用于分配给可授予的clientId
// stateless 标记以指示在这些资源上仅允许基于令牌的身份验证
// tokenStore token的存储方式(上一章节提到)
resources.resourceId(RESOURCE_ID).stateless(true).tokenStore(tokenStore)
//authenticationEntryPoint 认证异常流程处理返回
// tokenExtractor token获取方式,默认BearerTokenExtractor
// 从header获取token为空则从request.getParameter("access_token")
.authenticationEntryPoint(authenticationEntryPoint).tokenExtractor(unicomTokenExtractor);
}
其他属性:
accessDeniedHandler 权失败且主叫方已要求特定的内容类型响应
resourceTokenServices 加载 OAuth2Authentication 和 OAuth2AccessToken 的接口
eventPublisher 事件发布-订阅 根据异常的clazz触发不同event
@Configuration
@EnableResourceServer
protected class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
/**
* HttpSecurity配置这个与Spring Security类似:
* 请求匹配器,用来设置需要进行保护的资源路径,默认的情况下是保护资源服务的全部路径。
*/
@Override
public void configure(HttpSecurity http) throws Exception {
AuthenticationManager oauthAuthenticationManager = oauthAuthenticationManager(http);
//OAuth2核心过滤器
resourcesServerFilter = new OAuth2AuthenticationProcessingFilter();
resourcesServerFilter.setAuthenticationEntryPoint(authenticationEntryPoint);
//OAuth2AuthenticationManager,只有被OAuth2AuthenticationProcessingFilter拦截到的oauth2相关请求才被特殊的身份认证器处理。
resourcesServerFilter.setAuthenticationManager(oauthAuthenticationManager);
if (eventPublisher != null) {
//同上
resourcesServerFilter.setAuthenticationEventPublisher(eventPublisher);
}
if (tokenExtractor != null) {
//同上
resourcesServerFilter.setTokenExtractor(tokenExtractor);
}
resourcesServerFilter = postProcess(resourcesServerFilter);
resourcesServerFilter.setStateless(stateless);
if (!Boolean.TRUE.toString().equals(apolloCouponConfig.getOauthEnable())) {
// 不需要令牌,直接访问资源
http.authorizeRequests().anyRequest().permitAll();
} else {
http
//.anonymous().disable() //匿名访问
.antMatcher("/**") //匹配需要资源认证路径
.authorizeRequests()
.antMatchers("/swagger-ui.html", "/swagger-resources/**",
"/v2/api-docs/**", "/validatorUrl","/valid"
).permitAll() //匹配不需要资源认证路径
.anyRequest().authenticated()
.and()
.addFilterBefore(resourcesServerFilter, AbstractPreAuthenticatedProcessingFilter.class)
.exceptionHandling() //添加filter
.exceptionHandling().accessDeniedHandler(accessDeniedHandler) //异常处理
.authenticationEntryPoint(authenticationEntryPoint); //认证异常流程
}
}
}
accessDeniedHandler 异常 : 令牌不能访问该资源 (403)异常等
authenticationEntryPoint 异常 : 不传令牌,令牌错误(失效)等