gitHub 链接: https://github.com/vincent9309/seurity-oauth2
1 ResourceServerConfigurerAdapter (资源服务器配置)
内部关联了ResourceServerSecurityConfigurer和HttpSecurity。前者与资源安全配置相关,后者与http安全配置相关
@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 {
@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() //添加filte