Skip to main content

Notifications

Announcements

No record found.

Microsoft Dynamics CRM (Archived)

Passing access token to CRM API throws unauthorized(401) error

Posted on by Microsoft Employee

I'm trying to access a Dynamics CRM Online REST API with Azure AD oAuth 2 Authentication. In order to do so I followed these steps:

- I've registered a web application and/or web api in Azure
- Configured the permissions to Dynamics CRM to have Delegated permissions "Access CRM Online as organization user"
- And created a Key with a 1 year expiration and kept the Client ID generated.


My code

package com.palmtree.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 = "palmtreeinfotech6.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;
    }
}

I retrieve an access token successfully but when I try to do a httprequest to CRM I always get a 401 - Unauthorized status code. What am I missing?

*This post is locked for comments

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Passing access token to CRM API throws unauthorized(401) error

    Any help would be appreciated here.

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Passing access token to CRM API throws unauthorized(401) error

    Any update on this?

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Passing access token to CRM API throws unauthorized(401) error

    I followed the sample code here -

    github.com/.../CrmApplication.java

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!

Tips for Writing Effective Suggested Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

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

#2
Martin Dráb Profile Picture

Martin Dráb 230,235 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans