5

Я работаю над небольшим доказательством концепции для набора конечных точек, которые должны иметь возможность вызывать друг друга, проходящие токены, которые получают через поток учетных данных клиента OAuth 2 , Я использую Spring бутс и связанные с ними проекты по созданию этих конечных точек, и я запутался, почему рамки, кажется, очень упрямым о следующем коде:Есть ли простой способ загрузить конфигурацию клиента Spring OAuth

package com.example.client; 

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.beans.factory.annotation.Value; 
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 
import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.Configuration; 
import org.springframework.security.oauth2.client.OAuth2ClientContext; 
import org.springframework.security.oauth2.client.OAuth2RestOperations; 
import org.springframework.security.oauth2.client.OAuth2RestTemplate; 
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails; 
import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails; 
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client; 
import org.springframework.web.bind.annotation.PathVariable; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.springframework.web.bind.annotation.RestController; 

@Configuration 
@EnableAutoConfiguration 
@EnableOAuth2Client 
@RestController 
public class StuffClient { 

    @Value("${security.oauth2.client.access-token-uri}") 
    private String tokenUrl; 

    @Value("${security.oauth2.client.id}") 
    private String clientId; 

    @Value("${security.oauth2.client.client-secret}") 
    private String clientSecret; 

    @Value("${security.oauth2.client.grant-type}") 
    private String grantType; 

    @Autowired 
    private OAuth2RestOperations restTemplate; 

    private String uri = "http://localhost:8082/stuff/"; 

    @RequestMapping(value = "/client/{stuffName}", method = RequestMethod.GET) 
    public String client(@PathVariable("stuffName") String stuffName) { 
     String request = uri + stuffName; 
     return restTemplate.getForObject(request, String.class); 
    } 

    @Bean 
    public OAuth2RestOperations restTemplate(OAuth2ClientContext clientContext) { 
     return new OAuth2RestTemplate(resource(), clientContext); 
    } 

    @Bean 
    protected OAuth2ProtectedResourceDetails resource() { 
     ClientCredentialsResourceDetails resource = new ClientCredentialsResourceDetails(); 
     resource.setAccessTokenUri(tokenUrl); 
     resource.setClientId(clientId); 
     resource.setClientSecret(clientSecret); 
     resource.setGrantType(grantType); 
     return resource; 
    } 
} 

и сопровождающей файл конфигурации:

server: 
    port: 8081 

security: 
    basic: 
    enabled: false 
    oauth2: 
    client: 
     id: test-client 
     client-secret: test-secret 
     access-token-uri: http://localhost:8080/uaa/oauth/token 
     grant-type: client_credentials 

Выше работает точно так, как ожидалось. Если изменить security.oauth2.client.id к security.oauth2.client.client-id (как в коде Java и YAML), я получаю ошибку 500, первая строка которой является:

org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException: Unable to obtain a new access token for resource 'null'. The provider manager is not configured to support it. 

Код также отлично работает, если I жесткие кодовые значения для всех переменные экземпляра. Это, кажется, работает хорошо, на самом деле, в каждой перестановки заселение этих переменных экземпляра, за исключением того, где я использую @Value для заполнения clientId со значением security.oauth2.client.client-id

Так что мой главный вопрос: является основой фактически самоуверенности в этом очень особым образом? И если да, то почему? И могу ли я использовать эту упрямую, чтобы упростить мой код?

ответ

0

Я не уверен, какую версию с пружинной загрузкой вы используете. Я использую пружинные версии загрузчика 1.5.4.RELEASED и упростить свои коды,

вы можете придать OAuth2ProtectedResourceDetails как

@Autowired 
private OAuth2ProtectedResourceDetails resource; 

и создать OAuth2RestTemplate как

@Bean 
@Primary 
public OAuth2RestOperations restTemplate(OAuth2ClientContext clientContext) { 
    return new OAuth2RestTemplate(resource, clientContext); 
} 

образец YAML ..

### OAuth2 settings ### 
security: 
    user: 
    password: none 
    oauth2: 
    client: 
     accessTokenUri: ${auth-server}/oauth/token 
     userAuthorizationUri: ${auth-server}/oauth/authorize 
     clientId: myclient 
     clientSecret: secret 
    resource: 
     user-info-uri: ${auth-server}/sso/user 
     jwt: 
     keyValue: | 
      -----BEGIN PUBLIC KEY----- 
      your public key 
      -----END PUBLIC KEY----- 

И затем, используйте restTemplate экземпляр в контроллерах как

@Autowired 
private OAuth2RestOperations restTemplate; 

Я надеюсь, что некоторые из них помогут вам.