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
Stay up to date on forum activity by subscribing. You can also customize your in-app and email Notification settings across all subscriptions.
André Arnaud de Cal... 291,240 Super User 2024 Season 2
Martin Dráb 230,149 Most Valuable Professional
nmaenpaa 101,156