如何设置 OAuth2RestTemplate(更新后)

Posted

技术标签:

【中文标题】如何设置 OAuth2RestTemplate(更新后)【英文标题】:How to setup OAuth2RestTemplate (Post Updated) 【发布时间】:2013-01-17 15:09:05 【问题描述】:

我不确定我是否正确配置了 OAuth2RestTemplate。运行测试器类时出现以下错误。

    INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1df3248: defining beans [propertyConfigurer,dataSource,transactionManager,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,emf,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,accountRepository,questionRepository,org.springframework.data.repository.core.support.RepositoryInterfaceAwareBeanPostProcessor#0,org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0,org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor#0,jpaQuestionService,jpaAccountService,passwordEncoder,accountHelper,tradeConfig,org.springframework.data.repository.core.support.RepositoryInterfaceAwareBeanPostProcessor#1,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,baseOAuth2ProtectedResourceDetails,oAuth2ProtectedResourceDetails,accessTokenRequest,oAuth2ClientContext,oAuth2RestTemplate]; root of factory hierarchy
Exception in thread "main" error="access_denied", error_description="Unable to obtain a new access token for resource 'null'. The provider manager is not configured to support it."
    at org.springframework.security.oauth2.client.token.AccessTokenProviderChain.obtainNewAccessTokenInternal(AccessTokenProviderChain.java:146)
    at org.springframework.security.oauth2.client.token.AccessTokenProviderChain.obtainAccessToken(AccessTokenProviderChain.java:118)
    at org.springframework.security.oauth2.client.OAuth2RestTemplate.acquireAccessToken(OAuth2RestTemplate.java:216)
    at org.springframework.security.oauth2.client.OAuth2RestTemplate.getAccessToken(OAuth2RestTemplate.java:168)
    at org.springframework.security.oauth2.client.OAuth2RestTemplate.createRequest(OAuth2RestTemplate.java:89)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:442)
    at org.springframework.security.oauth2.client.OAuth2RestTemplate.doExecute(OAuth2RestTemplate.java:123)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:409)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:385)
    at com..main(Tester.java:44)

@Configuration
public class AppConfig 

@Bean
//@Scope(value="singleton", proxyMode=ScopedProxyMode.INTERFACES) 
public BaseOAuth2ProtectedResourceDetails baseOAuth2ProtectedResourceDetails()
    BaseOAuth2ProtectedResourceDetails baseOAuth2ProtectedResourceDetails =  new BaseOAuth2ProtectedResourceDetails();
    baseOAuth2ProtectedResourceDetails.setClientId(clientId);
    baseOAuth2ProtectedResourceDetails.setClientSecret(clientSecret);
    return baseOAuth2ProtectedResourceDetails; 


@Bean
public DefaultAccessTokenRequest accessTokenRequest()
    return new DefaultAccessTokenRequest();


@Bean
public OAuth2ClientContext oAuth2ClientContext()
    return new DefaultOAuth2ClientContext(accessTokenRequest());


@Bean
public OAuth2RestTemplate oAuth2RestTemplate()
    OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(baseOAuth2ProtectedResourceDetails(),oAuth2ClientContext());
    return restTemplate;


测试类

public class Tester 

public static void main(String[] args) 

    GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
    ctx.load("classpath*:jpa-app-context.xml");
    ctx.refresh();

EntityManagerFactory emf = (EntityManagerFactory) ctx.getBean("emf");
EntityManager em = emf.createEntityManager(); 
TransactionSynchronizationManager.bindResource(emf , new EntityManagerHolder(em)); 
OAuth2RestTemplate oAuth2RestTemplate = (OAuth2RestTemplate) ctx.getBean("oAuth2RestTemplate");

//OAuth2RestTemplate oAuth2RestTemplate  = ctx.getBean(OAuth2RestTemplate.class);
String uri="https:api..";


Object obj = oAuth2RestTemplate.exchange(uri, HttpMethod.POST, null, Object.class);
System.out.println("Tester Object: "+ obj.toString());


【问题讨论】:

Wilx:你能解决你的问题吗?如果有,能否提供完整的运行代码? 【参考方案1】:

我遇到了同样的异常,但使用了另一种受保护的资源类型。

通常,仅当AccessTokenProviderChain 无法为特定的*ProtectedResourceDetails 实例找到合适的*AccessTokenProvider 时才会引发异常。这意味着,当您尝试执行以下操作时:

ClientCredentialsResourceDetails resource = new ClientCredentialsResourceDetails();

resource.setAccessTokenUri(url);
resource.setClientId(clientId);
resource.setClientSecret(secret);
resource.setGrantType("password");

return resource;

代码需要client_credentials 授权类型,因为我们使用ClientCredentialsResourceDetails,但我们传递了password 值。

这里的代码适用于我的案例:

private OAuth2ProtectedResourceDetails withOAuth2Authentication(final String url, final String clientId, final String secret) 
    ClientCredentialsResourceDetails resource = new ClientCredentialsResourceDetails();

    resource.setAccessTokenUri(url);
    resource.setClientId(clientId);
    resource.setClientSecret(secret);
    // here you can provide additional properties such as scope etc.

    return resource;


@Bean
RestTemplate callbackClientV2() 
    AccessTokenRequest atr = new DefaultAccessTokenRequest();

    return new OAuth2RestTemplate(
                withOAuth2Authentication(v2ServerUrl, v2Username, v2Password),
                new DefaultOAuth2ClientContext(atr)
    );

【讨论】:

以上是关于如何设置 OAuth2RestTemplate(更新后)的主要内容,如果未能解决你的问题,请参考以下文章

带有预取 JWT 令牌的 OAuth2RestTemplate

将 OAuth2RestTemplate 公开为 AsyncRestTemplate

在安全上下文中保存 Oauth2RestTemplate/Client 存储

OAthe2 Login use OkHttpClient and OAuth2RestTemplate

OAuth2RestTemplate 身份验证问题被拒绝访问

Spring OAuth2 - CustomAuthenticationProvider登录问题