Skip to main content

Notifications

Microsoft Dynamics CRM (Archived)

Can't use Dynamics CRM token (401 Unauthorized)

Posted on by Microsoft Employee

I'm writing a simple android app in Java and recently implemented retrieving a token for a user (created a connected app in Azure, got app id etc.).

Trying to use the token with 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 = new OkHttpClient().newCall(request).execute();
  statusCode = response.code();
} 
...

//401 UNAUTHORIZED


Endpoints I used:

AUTHORIZE_ENDPOINT = "login.microsoftonline.com/.../authorize";
TOKEN_RETRIEVAL_ENDPOINT = "login.microsoftonline.com/.../token";
REST_ENDPOINT = "<url_to_crm>/api/data/v9.0/";

*This post is locked for comments

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Community AMA December 12th

Join us as we continue to demystify the Dynamics 365 Contact Center

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,240 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,149 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans