【问题标题】:consume Oauth2 (authorization code) rest api with spring rest template使用 Spring rest 模板使用 Oauth2(授权码)rest api
【发布时间】:2018-06-29 16:39:11
【问题描述】:

我正在尝试在 spring 集成项目中使用 rest web 服务。此 Web 服务受 oauth2(授权码)保护。知道如何实现这一点吗?

我尝试使用 OAuth2RestTemplate 但它给了我一个错误: 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();
}
  }
}

【问题讨论】:

  • 为了更具体,请在此处粘贴您的 oAuth 请求:第一个(用于授权代码)和第二个(用于访问令牌)。 o/w 它太宽泛,将被关闭。

标签: java spring-security oauth-2.0 spring-integration


【解决方案1】:

授权码流用于通过重定向在 Web 浏览器中对用户进行身份验证。它需要通过用户名和密码进行用户身份验证。

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

【讨论】:

  • 感谢指导
【解决方案2】:

如果服务受 oAuth2 保护,您必须使用 oAuth 规则才能访问资源服务器。这意味着您的应用需要注册并获取clientID和client-secret,然后您的应用的用户可以使用它来oAuth-connect ...

无论您如何调用调用,都必须使用 oAuth。 OAuth2RestTemplate 只是 Spring 为 oAuth 开发人员提供的 RestTemplate 实现,它抽象了一些与 oAuth 相关的逻辑......

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-18
    • 2018-07-30
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 2019-07-19
    • 2013-11-16
    相关资源
    最近更新 更多