本文介绍了使用spring rest模板使用Oauth2(授权码)rest api的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 spring 集成项目中使用休息 Web 服务.此 Web 服务使用 oauth2(授权代码)进行保护.知道如何实现这一点吗?

I'm trying to consume a rest web service in spring integration project. This web service is secured with oauth2 (authorization code).Any idea how to achieve this?

我尝试使用 OAuth2RestTemplate 但它给了我一个错误:org.springframework.security.oauth2.client.resource.UserRedirectRequiredException:需要重定向才能获得用户批准

I tried using OAuth2RestTemplate but it gave me an error:org.springframework.security.oauth2.client.resource.UserRedirectRequiredException: A redirect is required to get the users approval

下面是我的代码.

import java.util.Arrays;

import org.springframework.security.oauth2.client.token.AccessTokenRequest;
import org.springframework.security.oauth2.client.token.DefaultAccessTokenRequest;
import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeAccessTokenProvider;
import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails;

public class OAuth2Client1 {

  public static void main(String[] args) {

AuthorizationCodeResourceDetails resource = new AuthorizationCodeResourceDetails();
resource.setId("My Developer");
resource.setClientId("xxxxxx");
resource.setClientSecret("xxxxxx");
resource.setAccessTokenUri("https://api.infusionsoft.com/token");
resource.setUserAuthorizationUri("https://signin.infusionsoft.com/app/oauth/authorize");
resource.setPreEstablishedRedirectUri("https://myapps.com:8181/my_work");
resource.setScope(Arrays.asList("full"));
try {
  AuthorizationCodeAccessTokenProvider authProvider =
      new AuthorizationCodeAccessTokenProvider();
  AccessTokenRequest request = new DefaultAccessTokenRequest();
  String str = authProvider.obtainAuthorizationCode(resource, request);
  System.out.println(str);

} catch (Exception e) {
  e.printStackTrace();
}
  }
}

推荐答案

Authorization Code flow 用于通过重定向在 Web 浏览器中对用户进行身份验证.它需要通过用户名和密码进行用户身份验证.

Authorization Code flow is used to authenticate user in web browser through redirect. It requires user authentication by username and password.

您的案例是关于两个服务之间的通信,也称为 M2M(机器对机器).出于安全原因,不允许服务自行存储用户凭据.您应该使用仅需要客户端 ID 和客户端密码进行身份验证的客户端凭据流.这样你就可以使用 OAuth2RestTemplate.

Your case is about communication between two services, also called as M2M (machine-to-machine). Service is not allowed to store user credentials by itself due security reasons. You should use Client Credentials flow that requred only client id and client secret for authentication. So then you'll able to use OAuth2RestTemplate.

这篇关于使用spring rest模板使用Oauth2(授权码)rest api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 03:43
查看更多