5

I am attempting to integrate Azure AD login and Graph API into my angular2 website.

I have successfully implemented an ADAL login and redirect, built around a useful blog post here

From this I retrieved an id_token parameter that my adalservice can access. Currently this is acheived through a simple context.login() and catching the token in the redirect.

When I use this token to try and access Microsoft Graph, I receive an InvalidAuthenticationToken response stating Access Token validation failure.

API call with obtained "access_token"

I'm new to this stuff, so it could be that my call is intrinsically wrong, or that I lack certain permissions in AD, or my app reg lacks permissions. I've seen that I potentially need to request an access token with sufficient scope, yet I can find any examples of this.

Has anyone used this adalService library to obtain tokens for use with Graph API?

4
  • 1
    Could you provide the scopes you're using and the JSON you're getting back from the initial token request? Jun 28, 2017 at 16:33
  • This is related, and may be an alternate way to do what you are looking for: stackoverflow.com/questions/42551153/… Jun 29, 2017 at 0:22
  • @MarcLaFleur-MSFT My mistake was not calling acquireToken to obtain a token for the graph api scope. I am now able to obtain a working token and query the API. Thanks Jun 29, 2017 at 15:52
  • @JonnyKnottsvill, if possible , please show your code as an answer which will help others who meet same problem . The id token can't be used to make graph calls , audience validation will fail(show your error) since it should be https: //graph.microsoft.com/ . You could use this.context.acquireToken("https ://graph.microsoft.com/",function(message,token){} to get access token for graph api
    – Nan Yu
    Jun 30, 2017 at 1:28

2 Answers 2

4

I found a solution to my problem.

I was using the wrong token. I had to acquire a token specifically for Graph API. This meant I would have to first log in and then call this.context.acquireToken() like below:

this.context.acquireToken("https://graph.microsoft.com", function (error, id_token) {

    if (error || !id_token) {
        console.log('ADAL error occurred: ' + error);
    } 
    else {
            this.graphAccessToken = id_token;
            //Call graph API
    }
    }.bind(this)
);

It seems like it's essential that this process have 2 calls. Maybe someone can shed some light on whether I can immediately obtain a token with scope for the Graph API on login. Perhaps by setting required permissions for the app in Azure AD.

6
  • 3
    You've discovered the correct pattern! login() will get you an id token and "sign in" the user, then it's essential to call acquireToken() to get an access token for a resource. There are plans for the next version of adal.js to have an overload of acquireToken that can do an interactive request. This means you could bypass the login call! Watch for release on Github. Jun 30, 2017 at 17:08
  • I know it may sound stupid, but I'm getting the following: Error: Cannot match any routes. URL Segment: 'access_token'. The if condition returns 'ADAL error occurred: Token renewal operation failed due to timeout'. Do you guys have any suggestions for me, please?
    – AuroMetal
    Jan 4, 2018 at 9:21
  • Please post your complete solution. I think we need callbacks for 'access-token' created in angular. @AuroMetal were you able to get some solution which works end to end?
    – NitinSingh
    Jun 12, 2018 at 9:35
  • @NitinSingh Yes, I did! It was my own fault, I forgot to add { path: 'access_token', component: OAuthCallbackComponent, canActivate: [OAuthCallbackHandler] } to the route.
    – AuroMetal
    Jun 12, 2018 at 12:43
  • And this was same component and guard as the one added to the 'id_token' route or a bit different. The id_token one will set the user-profile in session but this one should do a bit different. Also, were you able to call the graph api properly? via the REST url or some graph wrapper? Would be good if you post your solution as answer here (since there are lots of points to cover)
    – NitinSingh
    Jun 12, 2018 at 13:55
4

Just to have a clarity for all, updating the end to end solution here again.

In case you do not have the base starter code, refer to this link Adal-JS Tutorial. This post only concerns with the customization involved.

Step 1: Configure the AdalService

(only new code is shown, other methods remain as it is)

export class AdalService {

    public get graphAccessToken() {
        return  sessionStorage[new AppConstants().User_Graph_Token];
    }

    public retrieveTokenForGraphAPI() {
        this.context.acquireToken('https://graph.microsoft.com', function (error, graph_token) {

            if (error || !graph_token) {
                console.log('ADAL error occurred: ' + error);
            } else {
                // Store token in sessionStorage
                sessionStorage[new AppConstants().User_Graph_Token] = graph_token;
                return;
            }
        }.bind(this)
        );
    }
 }

The code should have existing handlers for id_token callback and corresponding configuration in the routing. If not, please refer to link above for the initial code.

Now the requirement is retrieve the access_token once the id_token is retrieved. The access_token has additional field for "puid" which describes identifier for claims. This will be the step 2.

Step 2: Update LoginComponent

ngOnInit() {
    if (!this.adalService.isAuthenticated) {
      console.log('LoginComponent::Attempting login via adalService');
      this.adalService.login();
    } else {
      if (this.adalService.accessTokenForGraph == null) {
        console.log('LoginComponent::Login valid, attempting graph token retrieval');
        this.adalService.retrieveTokenForGraphAPI();
      }
   }

Now the token is retrieved and stored for later use.

Step 3: Update Routing for 'access_token' callback

Similar to the 'id_token' callback, we need to add additional callback route for the access_token. The callback components will remain same. Their code is as described in the main link. Note that *access_token" endpoint is MS provided, hence be careful not to change the name.

  { path: 'access_token', component:  OAuthCallbackComponent, canActivate: [OAuthCallbackHandler] },
  { path: 'id_token', component: OAuthCallbackComponent, canActivate: [OAuthCallbackHandler] }

Step 4: Use the token wherever required

const bearer = this.adalService.graphAccessToken();
1
  • 1
    Sorry for the late reply. That's exactly what I've done (including the exact same tutorial)! +1 for the very detailed answer.
    – AuroMetal
    Jun 13, 2018 at 17:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.