由于本項目資源服務(wù)和認證服務(wù)不在同一服務(wù)上纵朋,這里token‘認證使用遠程認證服務(wù)器認證
修改資源服務(wù)器的配置,主要在配置類繼承資源配置ResourceServerConfigurerAdapter的configure方法
1) 設(shè)置RestTemplate笼痛,默認RestTemplate有些格式無法解析,配置相關(guān)解析器
@LoadBalanced
@Bean
public RestTemplate restTemplate() {
//httpRequestFactory()
RestTemplate restTemplate = new RestTemplate();
List<HttpMessageConverter<?>> converters = restTemplate.getMessageConverters();
for (HttpMessageConverter<?> converter : converters) {
if (converter instanceof MappingJackson2HttpMessageConverter) {
MappingJackson2HttpMessageConverter jsonConverter = (MappingJackson2HttpMessageConverter) converter;
jsonConverter.setObjectMapper(new ObjectMapper());
jsonConverter.setSupportedMediaTypes(ImmutableList.of(new MediaType("application", "json", MappingJackson2HttpMessageConverter.DEFAULT_CHARSET), new MediaType("text", "javascript", MappingJackson2HttpMessageConverter.DEFAULT_CHARSET)));
}
}
return restTemplate;
}
2) 設(shè)置token解析器牺堰,因為認證服務(wù)使用的為默認解析器,這里保持一致
@Bean
public AccessTokenConverter accessTokenConverter() {
return new DefaultAccessTokenConverter();
}
- 設(shè)置遠程遠程調(diào)用服務(wù)颅围,以及配置
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.tokenServices(tokenServices());//.resourceId(SPARKLR_RESOURCE_ID);
}
@Bean
public ResourceServerTokenServices tokenServices() {
RemoteTokenServices remoteTokenServices = new RemoteTokenServices();
remoteTokenServices.setCheckTokenEndpointUrl("https://security-service/oauth/check_token");
//這里硬編碼客戶端信息伟葫,服務(wù)端硬編碼保存在內(nèi)存里,生產(chǎn)上請修改
remoteTokenServices.setClientId("client");
remoteTokenServices.setClientSecret("password");
remoteTokenServices.setRestTemplate(restTemplate());
remoteTokenServices.setAccessTokenConverter(accessTokenConverter());
return remoteTokenServices;
}
認證服務(wù)的修改
1) 為了是校驗請求通過院促,認證服務(wù)筏养,修改配置public class OAuth2Config extends AuthorizationServerConfigurerAdapter
增加.checkTokenAccess("permitAll()")
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security
// 開啟/oauth/token_key驗證端口無權(quán)限訪問
.tokenKeyAccess("permitAll()")
.checkTokenAccess("permitAll()")
.passwordEncoder(new BCryptPasswordEncoder())
// 請求/oauth/token的,如果配置支持allowFormAuthenticationForClients的常拓,且url中有client_id和client_secret的會走ClientCredentialsTokenEndpointFilter
.allowFormAuthenticationForClients();
}
測試如下
- 正確攜帶token訪問api-server的接口
-
不使用token渐溶、或者錯誤token使用,返回401或者token異常500