我有一个Spring Boot2应用程序,它使用OIDC/OAuth2进行身份验证和授权。
我们的目标是有一个图形用户界面,其中用户被重定向到授权服务器,以便通过authorization_code授权类型登录。
此外,该应用程序还为其他服务器应用程序提供REST web服务。服务器到服务器的通信应该受到来自同一授权服务器的client_credentials授权类型的保护。
该应用程序还需要从其他服务器应用程序访问REST web服务,而无需用户交互,因此需要client_credentials授权类型的令牌。
现在,我需要在我的应用程序中使用一个持有者令牌,以便访问其他服务器web服务。目前,我使用RestTemplate通过发送一个HTTP请求来检索它:
private OAuth2AccessToken getBearerToken(ClientRegistration clientRegistration){
String tokenUri = clientRegistration.getProviderDetails().getTokenUri();
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("grant_type", clientRegistration.getAuthorizationGrantType().getValue());
map.add("client_id",clientRegistration.getClientId());
map.add("client_secret",clientRegistration.getClientSecret());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(map, headers);
ResponseEntity<DefaultOAuth2AccessToken> exchange = restTemplate.exchange(tokenUri, HttpMethod.POST, entity, DefaultOAuth2AccessToken.class);
LOGGER.info(exchange.getBody().getValue());
return exchange.getBody();
}现在,我已经在application.yml中定义了多个具有不同授权类型的OAuth2客户端,并且我从ClientRegistrationRepository获得了client_credentials ClientRegistration。但是有没有办法利用Spring-Security5 OAuth2客户端功能来为我检索持有者令牌呢?
我尝试了以下几种方法:
ClientRegistration adfsclient = clientRegistrationRepository.findByRegistrationId("client_credentials");
OAuth2AuthorizationContext.Builder builder = OAuth2AuthorizationContext.withClientRegistration(adfsclient);
OAuth2AuthorizationContext build = builder.build();
OAuth2AuthorizedClient authorize = clientProvider.authorize(build);但我得到的是:
java.lang.IllegalArgumentException: principal cannot be null
at org.springframework.util.Assert.notNull(Assert.java:198) ~[spring-core-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.security.oauth2.client.OAuth2AuthorizationContext$Builder.build(OAuth2AuthorizationContext.java:199) ~[spring-security-oauth2-client-5.2.1.RELEASE.jar:na]
at my.test.sso.adfs.WebAPICaller.callURI(WebAPICaller.java:36) ~[classes/:na]
....
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_25]但我没有校长,实际上我也不需要。有没有其他方法可以利用Spring Security OAuth2客户端来获取持有者令牌?
Thx,Pero
发布于 2020-02-21 01:32:49
我发现OAuth2RestTemplate正在做我需要的事情。
@Bean()
@ConfigurationProperties(prefix ="spring.security.oauth2.client.registration.adfs")
protected ClientCredentialsResourceDetails oAuthDetails() {
return new ClientCredentialsResourceDetails();
}
@Bean
public OAuth2RestTemplate oAuth2RestTemplate(ClientCredentialsResourceDetails oAuthDetails){
return new OAuth2RestTemplate(oAuthDetails);
}最终通过调用:
OAuth2AccessToken accessToken = oAuth2RestTemplate.getAccessToken();这是我需要的。
甚至可以使用here中描述的WebClient实例来获取令牌
https://stackoverflow.com/questions/60168407
复制相似问题