小编典典

如何使用OAuth2RestTemplate?

spring

我正在尝试了解如何使用OAuth2RestTemplate对象来消耗我的OAuth2安全的REST服务(该服务在不同的项目下运行,并且假设在其他服务器上也是如此…)

我的休息服务是:

http://localhost:8082/app/helloworld

->访问此URL会产生错误,因为我未通过身份验证

要请求令牌,我将前往:

http://localhost:8082/app/oauth/token?grant_type=password&client_id=restapp&client_secret=restapp&username=**USERNAME**&password=**PASSWORD**

收到令牌后,我可以使用以下URL(插入示例令牌)连接到REST API。

http://localhost:8082/app/helloworld/?access_token=**4855f557-c6ee-43b7-8617-c24591965206**

现在,我的问题是如何实现第二个可以使用此OAuth2安全的REST API的应用程序?我确实没有找到任何可以提供用户名和密码(例如来自登录表单)的工作示例,然后生成了令牌,可以将其重新使用以从REST API中获取数据。

我目前尝试使用以下对象进行操作:

BaseOAuth2ProtectedResourceDetails baseOAuth2ProtectedResourceDetails =  new BaseOAuth2ProtectedResourceDetails();
baseOAuth2ProtectedResourceDetails.setClientId("restapp");
baseOAuth2ProtectedResourceDetails.setClientSecret("restapp");
baseOAuth2ProtectedResourceDetails.setGrantType("password");
// how to set user name and password ???

DefaultAccessTokenRequest accessTokenRequest = new DefaultAccessTokenRequest();
OAuth2ClientContext oAuth2ClientContext = new DefaultOAuth2ClientContext(accessTokenRequest());

OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(baseOAuth2ProtectedResourceDetails,oAuth2ClientContext);

但这是行不通的:(


阅读 2546

收藏
2020-04-12

共1个答案

小编典典

在你的情况下,你不能仅对所有内容使用默认类或基类,而是有多个实现类OAuth2ProtectedResourceDetails。该配置取决于你配置OAuth服务的方式,但是从你的curl连接中假设,我建议:

@EnableOAuth2Client
@Configuration
class MyConfig{

    @Value("${oauth.resource:http://localhost:8082}")
    private String baseUrl;
    @Value("${oauth.authorize:http://localhost:8082/oauth/authorize}")
    private String authorizeUrl;
    @Value("${oauth.token:http://localhost:8082/oauth/token}")
    private String tokenUrl;

    @Bean
    protected OAuth2ProtectedResourceDetails resource() {
        ResourceOwnerPasswordResourceDetails resource;
        resource = new ResourceOwnerPasswordResourceDetails();

        List scopes = new ArrayList<String>(2);
        scopes.add("write");
        scopes.add("read");
        resource.setAccessTokenUri(tokenUrl);
        resource.setClientId("restapp");
        resource.setClientSecret("restapp");
        resource.setGrantType("password");
        resource.setScope(scopes);
        resource.setUsername("**USERNAME**");
        resource.setPassword("**PASSWORD**");
        return resource;
    }

    @Bean
    public OAuth2RestOperations restTemplate() {
        AccessTokenRequest atr = new DefaultAccessTokenRequest();
        return new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(atr));
    }
}

@Service
@SuppressWarnings("unchecked")
class MyService {

    @Autowired
    private OAuth2RestOperations restTemplate;

    public MyService() {
        restTemplate.getAccessToken();
    }
}

不要忘记@EnableOAuth2Client你的配置类,我也建议你尝试首先使用正在使用的url与curl配合使用,并尝试使用调试器对其进行跟踪,因为由于安全性原因,很多异常只是被消耗掉而从未打印出来,因此很难找到问题所在。你应该使用loggerdebug启用集。

2020-04-12