Search code examples
javaandroidoauth-2.0dynamics-crmhttp-status-code-401

Can't use Dynamics CRM token (401 Unauthorized)


I'm writing a simple android app in Java and recently implemented retrieving a token for a user from Microsoft Dynamics CRM (I have created a connected app in Azure, got application id, secret etc).

I want other users of this application to be able to connect to their CRMs and organizations.

Now I'm trying to use the token with the REST API and getting 401 error. Read all the related answers here, nothing helped. The code I'm using:

//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

Endpoints I used:

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/


Solution

  • Here are two sample Java projects that connect and authenticate with the Dynamics Web API via Azure:

    Link 1

    Link 2

    Hope this helps.