有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Spring Boot 2 SpringSecurity 5 OAuth2对客户端凭据授予类型的支持

我有一个SpringBoot2应用程序,使用OIDC/OAuth2进行身份验证和授权

目标是拥有一个GUI,用户被重定向到授权服务器,以便通过授权代码授权类型登录

此外,该应用程序还为其他服务器应用程序提供REST web服务。服务器到服务器的通信应通过来自同一授权服务器的客户端\u凭据授予类型进行保护

该应用程序还需要从其他服务器应用程序访问REST web服务,而无需用户交互,因此需要具有client_凭据授权类型的令牌

现在,我需要在我的应用程序中使用承载令牌才能访问其他服务器web服务。 目前,我通过发送HTTP请求,使用RestTemplate检索它:

 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();
}

现在,我在应用程序中定义了多个具有不同授权类型的OAuth2客户机。yml和我从ClientRegistrationRepository中获取客户端凭据ClientRegistration。但是有没有一种方法可以利用SpringSecurity5OAuth2客户端功能为我检索承载令牌呢

我尝试了以下方法:

 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]

但我没有校长,实际上我也不需要校长。有没有其他方法可以利用SpringSecurityOAuth2客户端来获取承载令牌

Thx,Pero


共 (1) 个答案

  1. # 1 楼答案

    我发现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();
    

    这是我需要的

    甚至可以使用WebClient实例获取令牌 描述here