无法使用Dynamics CRM令牌(401未经授权)

时间:2017-10-27 09:17:58

标签: java android oauth-2.0 dynamics-crm http-status-code-401

我正在用Java编写一个简单的Android应用程序,最近实现了从Microsoft Dynamics CRM中为用户检索令牌(我在Azure中创建了一个连接的应用程序,获得了应用程序ID,秘密等)。

我希望此应用程序的其他用户能够连接到他们的CRM和组织。

现在我正在尝试将令牌与REST API一起使用并获得401错误。 在这里阅读所有相关答案,没有任何帮助。我正在使用的代码:

//retrieved the authorization code by this url:
mAuthorizationUrl = Configuration.AUTHORIZE_ENDPOINT + "?response_type=code&client_id=" 
+ Configuration.CLIENT_ID + "&redirect_uri=" + Configuration.REDIRECT_URI;

...

//Retrieving access_token:
String body_content = "grant_type=authorization_code&client_id=" + 
Configuration.CLIENT_ID + "&redirect_uri=" + Configuration.REDIRECT_URI 
+ "&code=" + code + "&resource=" + Configuration.CLIENT_ID;
//I don't have app URI (resource) in Azure, so I used app id (client id).
//This worked (see above).

RequestBody body = RequestBody.create(
                   MediaType.parse("application/x-www-form-urlencoded; charset=utf-8"), 
                   body_content);
Request request = new Request.Builder()
.url(Configuration.TOKEN_RETRIEVAL_ENDPOINT)
.post(body)
.build();

Response response = new OkHttpClient().newCall(request).execute();

String responseString = response.body().string();
JSONObject json = new JSONObject(responseString);
String token = json.getString("access_token");

//NOT WORKING CODE:
OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
.protocols(Collections.singletonList(Protocol.HTTP_1_1))
.build();

Map<String, String> headers = new ArrayMap<>();
headers.put("Authorization", "Bearer " + token));
headers.put("Accept", "application/json");

request = new Request.Builder()
.url(Configuration.REST_ENDPOINT)
.headers(Headers.of(headers))
.build();
try {
  response = okHttpClient
  .newCall(request)
  .execute();
  statusCode = response.code();
} 
...

//401 UNAUTHORIZED

我使用的端点:

AUTHORIZE_ENDPOINT = https://login.microsoftonline.com/common/oauth2/authorize

TOKEN_RETRIEVAL_ENDPOINT = https://login.microsoftonline.com/common/oauth2/token

REST_ENDPOINT = url_to_crm /api/data/v9.0 /

1 个答案:

答案 0 :(得分:1)

以下是通过Azure连接和验证Dynamics Web API的两个示例Java项目:

Link 1

Link 2

希望这有帮助。