gpt4 book ai didi

java - 将访问 token 传递给 CRM API 会引发未经授权的 (401) 错误

转载 作者:太空宇宙 更新时间:2023-11-04 11:51:19 25 4
gpt4 key购买 nike

我正在尝试使用 Azure AD oAuth 2 身份验证访问 Dynamics CRM Online REST API。为此,我按照以下步骤操作:

  • 我已在 Azure 中注册了 Web 应用程序和/或 Web API
  • 将 Dynamics CRM 的权限配置为具有委派权限“以组织用户身份访问 CRM Online”
  • 并创建了一个有效期为 1 年的 key 并保留生成的客户端 ID。

我的代码:

package com.JasonLattimer.crm.auth;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import javax.naming.ServiceUnavailableException;

import com.microsoft.aad.adal4j.AuthenticationContext;
import com.microsoft.aad.adal4j.AuthenticationResult;
import com.microsoft.aad.adal4j.ClientCredential;

import net.minidev.json.JSONObject;
import net.minidev.json.JSONValue;

public class App {


// CRM URL
private final static String RESOURCE = "xxxxxx.crm8.dynamics.com";
private final static String CLIENT_ID = "xxxxxxx-xxxxx-xxxxxxx-xxxxxxxxx";
private final static String CLIENT_SECRET_KEY = "xxxxxxxxxxxxxxxxxxxxxx";
private final static String TENANTID = "xxxxxxxxxxx-xxxx-xxxxx-xxxxxxx";
private final static String AUTHORITY = "login.microsoftonline.com" + TENANTID + "/oauth2/authorize";

public static void main(String args[]) throws Exception {
AuthenticationResult result = getAccessTokenFromUserCredentials();
System.out.println("Access Token - " + result.getAccessToken());
System.out.println("Token expires on - " + result.getExpiresOn());

//String userId = WhoAmI(result.getAccessToken());
//System.out.println("UserId - " + userId);

String fullname = FindFullname(result.getAccessToken(), "2b8fc8ca-86cd-e611-8109-c4346bdc0e01");
System.out.println("Fullname: " + fullname);
}

private static AuthenticationResult getAccessTokenFromUserCredentials() throws Exception {

AuthenticationContext authContext = null;
AuthenticationResult authResult = null;
ExecutorService service = null;

try {
service = Executors.newFixedThreadPool(1);
authContext = new AuthenticationContext(AUTHORITY, false, service);

ClientCredential clientCred = new ClientCredential(CLIENT_ID, CLIENT_SECRET_KEY);
Future<AuthenticationResult> future = authContext.acquireToken(RESOURCE, clientCred, null);
authResult = future.get();
} catch (Exception ex) {
System.out.println(ex);
} finally {
service.shutdown();
}

if (authResult == null) {
throw new ServiceUnavailableException("authentication result was null");
}
return authResult;
}

private static String FindFullname(String token, String userId) throws MalformedURLException, IOException {
System.out.println("AAAAAAAAAAAAAAAAAA");
HttpURLConnection connection = null;
//The URL will change in 2016 to include the API version - /api/data/v8.0/systemusers
URL url = new URL(RESOURCE + "/api/data/systemusers(" + userId + ")?$select=fullname");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("OData-MaxVersion", "4.0");
connection.setRequestProperty("OData-Version", "4.0");
connection.setRequestProperty("Accept", "application/json");
connection.addRequestProperty("Authorization", "Bearer " + token);

int responseCode = connection.getResponseCode();

BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();

Object jResponse;
jResponse = JSONValue.parse(response.toString());
JSONObject jObject = (JSONObject) jResponse;
String fullname = jObject.get("fullname").toString();
System.out.println("FULL NAME" + fullname);
return fullname;
}

private static String WhoAmI(String token) throws MalformedURLException, IOException {
HttpURLConnection connection = null;
//The URL will change in 2016 to include the API version - /api/data/v8.0/WhoAmI
URL url = new URL(RESOURCE + "/api/data/WhoAmI");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("OData-MaxVersion", "4.0");
connection.setRequestProperty("OData-Version", "4.0");
connection.setRequestProperty("Accept", "application/json");
connection.addRequestProperty("Authorization", "Bearer " + token);

int responseCode = connection.getResponseCode();

BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();

Object jResponse;
jResponse = JSONValue.parse(response.toString());
JSONObject jObject = (JSONObject) jResponse;
String userId = jObject.get("UserId").toString();
return userId;
}
}

我成功检索了访问 token ,但当我尝试向 CRM 发出 httprequest 时,我总是收到 401 - 未经授权的状态代码。我错过了什么?

最佳答案

您有 2 个选择:

  1. 您在 CRM 中作为“普通”用户进行身份验证的旧方法(您需要他们的密码,但可以避免弹出流程)。 C# 示例 here .
  2. 新方法是“服务器到服务器身份验证”,它要求您创建 Application User 。注意此示例也是 C# 语言,但 Java 中的 ADAL 代码应该非常相似。

关于java - 将访问 token 传递给 CRM API 会引发未经授权的 (401) 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41806328/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com