【问题标题】:Accessing bearer token in java using post API使用 post API 在 java 中访问不记名令牌
【发布时间】:2020-10-15 18:43:21
【问题描述】:

我必须调用 url 来获取访问令牌以调用后续 API。此令牌端点由basic authentication 保护。

token endpoint:- https://xxxxxx.identity.c9dev2.oc9qadev.com/oauth2/v1/token
      username: "xxx-ccc"
      password: "avcdada"
      grant_type: client_credentials
      scope: https://xxxxxx.digitalassistant.oci.oc-test.com/api/v1
      request type: POST

我无法在 java 中使用上述内容。我尝试了很多代码,但没有一个工作。可以吗,请帮我一些链接。我是java 的新手,并且很挣扎。下面是我使用的代码。它不工作。

package postapicall;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;

public class PostApi1 {
    
     public static void main(String []args)
     {
         
    
    try
    {
        String authorization = "";
        String url= "https://idcs-82972921e42641b1bf08128c3d93a19c.identity.c9dev2.oc9qadev.com/oauth2/v1/token";
        String username = "idcs-oda-9417f93560b94eb8a2e2a4c9aac9a3ff-t0_APPID";
        String password = "244ae8e2-6f71-4af2-b5cc-9110890d1456";
        URL address = new URL(url);
        HttpURLConnection hc = (HttpURLConnection) address.openConnection();

        hc.setDoOutput(true);
        hc.setDoInput(true);
        hc.setUseCaches(false);

        if (username != null && password != null) {
            authorization = username + ":" + password;
        }

        if (authorization != null) {
            byte[] encodedBytes;
            encodedBytes = Base64.encode(authorization.getBytes(), 0);
            authorization = "Basic " + encodedBytes;
            hc.setRequestProperty("Authorization", authorization);
        }

   }
    catch(Exception e)
    {
        System.out.println(e.getMessage());
    }
    
}

}

【问题讨论】:

    标签: java rest access-token spring-security-oauth2 bearer-token


    【解决方案1】:

    首先,我不知道encodedBytes = Base64.encode(authorization.getBytes(), 0);这一行在你的机器上是如何编译的(没有Base64#encode方法)。

    假设您使用 Java 1.8+,更改:

    byte[] encodedBytes;
    encodedBytes = Base64.encode(authorization.getBytes(), 0);
    authorization = "Basic " + encodedBytes;
    hc.setRequestProperty("Authorization", authorization)
    

    String encodedCredentials = Base64.getEncoder().encodeToString(authorization.getBytes());
    hc.setRequestProperty("Authorization", "Basic " + encodedCredentials);
    

    应该可以解决问题。

    【讨论】:

    • 感谢@Cedric,它现在正在编译。你能告诉我如何使用范围、内容类型等从令牌端点获取令牌。因为我是新手,所以代码不完整。
    • 取决于端点想要如何接收它。 grant_typescope 可能需要在消息头中或作为查询参数 (<url>?scope=xxx&grant_type=xxx)。
    猜你喜欢
    • 2017-04-12
    • 1970-01-01
    • 2021-03-30
    • 2016-01-22
    • 2021-11-10
    • 1970-01-01
    • 1970-01-01
    • 2022-09-30
    • 2017-10-21
    相关资源
    最近更新 更多