如何使用 OAuth2RestTemplate? [英] How to use OAuth2RestTemplate?

查看:86
本文介绍了如何使用 OAuth2RestTemplate?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试了解如何使用 OAuth2RestTemplate 对象来使用我的 OAuth2 安全 REST 服务(它在不同的项目下运行,让我们假设也在不同的服务器上等...)

I'm trying to understand how to use a OAuth2RestTemplate object to consume my OAuth2 secured REST service (which is running under a different project and let's assume also on a different server etc...)

我的 REST 服务的一个例子是:

An example of my REST service is:

http://localhost:8082/app/helloworld

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

-> Accessing this URL generates an error as I am not authenticated

要请求令牌,我会去:

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

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

After I receive the token I can then connect to the REST API by using the following URL (example token inserted)

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

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

Now my question is how do I implement a second application which can consume this OAuth2 secured REST API? I really haven't found any working examples where you provide the user name and password (e.g. coming from a login form) and then a token is generated which can be re-used to get data from the REST API.

我目前尝试使用以下对象:

I currently tried something with the following objects:

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

但这根本行不通:(

非常感谢任何想法、工作示例或教程的链接.

Any ideas, links to working examples or tutorials are greatly appreciated.

推荐答案

您可以在此处找到编写 OAuth 客户端的示例:

You can find examples for writing OAuth clients here:

在您的情况下,您不能只对所有内容使用默认类或基类,您有多个实现 OAuth2ProtectedResourceDetails 的类.配置取决于您如何配置 OAuth 服务,但假设我建议使用 curl 连接:

In your case you can't just use default or base classes for everything, you have a multiple classes Implementing OAuth2ProtectedResourceDetails. The configuration depends of how you configured your OAuth service but assuming from your curl connections I would recommend:

@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 启用集一起使用.祝你好运

Do not forget about @EnableOAuth2Client on your config class, also I would suggest to try that the urls you are using are working with curl first, also try to trace it with the debugger because lot of exceptions are just consumed and never printed out due security reasons, so it gets little hard to find where the issue is. You should use logger with debug enabled set. Good luck

我在 github 上上传了示例 springboot 应用程序 https://github.com/mariubog/oauth-client-样本描述您的情况,因为我找不到您的场景的任何示例.

I uploaded sample springboot app on github https://github.com/mariubog/oauth-client-sample to depict your situation because I could not find any samples for your scenario .

这篇关于如何使用 OAuth2RestTemplate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆