3

I'm developing a SPA app in React that needs to integrate with AzureAD and the GraphAPI (implicit flow).

My question is very similar to: ADAL.js - Obtaining Microsoft Graph Access Token with id_token ... but the answer doesn't show me enough code to get me on my way.

So far, using just adal.js (v1.0.14), I can login & get an id_token, but I can't figure out how to use it to get access to make Graph API calls.

UPDATE: I know I'm correctly registered with the Azure portal, because I was able to login and get recent docs without adal.js or any lib ... just using home-made ajax calls.

Here's my code, which does the login/redirect, and then tries to get my recent docs:

// Initial setup      
var adalCfg = {
  instance              : 'https://login.microsoftonline.com/',
  tenant                : 'common',
  clientId              : 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
  postLogoutRedirectUri : window.location.origin,
  extraQueryParameter   : 'scope=Mail.ReadWrite+Files.Read+Files.ReadWrite+User.ReadBasic.All' // Is this the proper way to specify what resources I need access to?
};

var authContext = new Adal(adalCfg);

if(!authContext.getCachedUser()) {
  authContext.login();  // redirects MS login page successfully
}

// Check For & Handle Redirect From AAD After Login
var isCallback = authContext.isCallback(window.location.hash); // Checks if the URL fragment contains access token, id token or error_description.
if(isCallback) {
  authContext.handleWindowCallback(); // extracts the hash, processes the token or error, saves it in the cache and calls the registered callbacks with the result.
}

if (isCallback && !authContext.getLoginError()) {
  window.location = authContext._getItem(authContext.CONSTANTS.STORAGE.LOGIN_REQUEST); // redirects back to /
}

// Try to get my recent docs - FAILS with InvalidAuthenticationToken error
// UDPATED authContext.acquireToken(authContext.config.clientId, function (error, token) {
authContext.acquireToken('https://graph.microsoft.com', function (error, token) {

  $.ajax({
    url: 'https://graph.microsoft.com/v1.0/me/drive/recent',
    headers:{'authorization':'Bearer '+ token},
    type:'GET',
    dataType:'json'
  }).done(function(res) {
    console.log(res['value']);
  });

});

What have I got wrong?


Update 2: I changed acquireToken per Fei's answer, but now when adal silently gets an access token for my resource, it fails to pass it to my API call.

Updated code:

    adalCfg.endpoints.graphApiUri = "https://graph.microsoft.com";

    authContext.acquireToken(adalCfg.endpoints.graphApiUri, function (errorDesc, token, error) {
      console.log('errorDesc = ' + errorDesc)
      console.log('token = ' + token)      
      console.log('error = ' + error)

      $.ajax({
        url: adalCfg.endpoints.graphApiUri + '/v1.0/me/drive/recent',
        headers:{'authorization':'Bearer '+ token},
        type:'GET',
        dataType:'json'
      }).done(function(res) {
        console.log(res['value']);
      });

    });

And console output:

Token not being captured

The image shows the req for a token, which appears to succeed, because the next GET contains the access_token in the hash. However, acquireToken passes a null token to my Graph API call.

However, if I manually grab the access token out of the hash, I can successfully make the Graph API call.

Why doesn't adal pass the access token to my API call? It came back and is valid.

3
  • Is it helpful to and the endpoints to the config like https://graph.windows.net. I also update the post to add a code sample which calling the Microsoft Graph. If you still have the issue, you may share a runable code sample to help reproducing this issue. Commented Jul 13, 2017 at 9:28
  • Is the issue fixed? If not, please check the code sample I update to see whether it is helpful. And if you still have the problem, you can share a runable code sample to help us to reproduce this issue. Commented Jul 18, 2017 at 8:23
  • Back to this - @FeiXue-MSFT , yes your code sample works for me. I accepted your answer. Commented Jul 20, 2017 at 21:44

1 Answer 1

3

To call the Microsoft Graph, we need to get the specific token for this resource. Based on the code you were acquire the token using the authContext.config.clientId.

If you register the app on Azure portal, to get the access token for the Microsoft Graph, you need to replace authContext.config.clientId with https://graph.microsoft.com.

And to call the REST sucessfully, we need to make sure having the enough permission. For example, to list recent files, one of the following scopes is required:Files.Read,Files.ReadWrite,Files.Read.All,Files.ReadWrite.All,Sites.Read.All,Sites.ReadWrite.All(refer here).

Update

<html>
<head>
<script src="\node_modules\jquery\dist\jquery.js"></script>
<script src="node_modules\adal-angular\lib\adal.js"></script>
</head>
<body>

<button id="login"> login</button>
<button id="clickMe">click me</button>
<script>


$(function () {
    var endpoints = {
          "https://graph.microsoft.com": "https://graph.microsoft.com"
    };
    window.config = {
        tenant: 'xxxx.onmicrosoft.com',
        clientId: 'xxxxxxxxxxxxxxxxx',
        endpoints: endpoints
    };
    window.authContext = new AuthenticationContext(config);


    $("#login").click(function () {
        window.authContext.login();
    });

    $("#clickMe").click(function () {
        var user = window.authContext.getCachedUser();
        console.log(user);

        window.authContext.acquireToken('https://graph.microsoft.com', function (error, token) {
            console.log(error);
            console.log(token);

             $.ajax({
        url: 'https://graph.microsoft.com/v1.0/me/',
        headers:{'authorization':'Bearer '+ token},
        type:'GET',
        dataType:'json'
      }).done(function(res) {
        console.log(res['userPrincipalName']);
      });

    });
        }
            );

    function init(){
        if(window.location.hash!="")
            window.authContext.handleWindowCallback(window.location.hash);
    }

    init();
});
</script>


</body>
</html>
Sign up to request clarification or add additional context in comments.

4 Comments

Where do I get ClientID? We have an App registered in Azure AD with Graph API Rights. I want host this code on a web server outside of Azure (unrelated to the registered app) and don't want to register it. Also, how can or should I use App Secret and Reply URLs of the registered app?
Hi got a second?
I am facing similar issue I can login using adal but when i pass the token in headers just like mentioned above its returning following response { "error": { "code": "InvalidAuthenticationToken", "message": "Access token validation failure.", "innerError": { "request-id": "2600e8e9-27ea-488a-a5ab-cae0d4200e7c", "date": "2018-06-29T11:30:00" } } }
I am using adal.js in my project and when i am calling graph api, I am getting logged out when I am passing 'graph.microsoft.com' instead of client id

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.