简体   繁体   中英

How to Get a valid access token for my API and Microsoft Graph from Azure Active Directory?

I am trying to set up a spa javascript app which logs the user into our azure active directory tenant and then retrieves profile information from microsoft graph and calls an azure function written in c# core (my API).

I have separate application registrations set up for my website and the api in azure active directory.

I'm using the MSAL.js library in the javascript spa website and I'm using the newer microsoft identity / v2.0 endpoints.

The SPA app signs into active directory as expected and is able to use the access token to make the call to graph for the profile information. In my azure function I validate the token and this fails with the error "IDX10511: Signature validation failed. Keys tried: ....."

Now if I remove Microsoft graph from the scopes when requesting a token I get a token that when passed to the azure function validates perfectly well but I can no longer retrieve profile data in the spa app?

How do I get both to work?

Its also worth noting that ive tested the tokens with jwt.io and it is also unable to verify the signature when graph is used.

Heres how I'm getting my token:

var msalConfig = {
  auth: {
    redirectUri: window.location.origin, // forces top level instead of specific login pages - fixes deep link issues.
    clientId: "Client ID of the website app", //This is your client ID
    authority:
      "https://login.microsoftonline.com/my-tennant-guid" //This is your tenant info
  },

  cache: {
    cacheLocation: "localStorage",
    storeAuthStateInCookie: true
  }
};
const msalUserAgent = new Msal.UserAgentApplication(msalConfig);


var requestObj = {
  scopes: ["User.Read", "api://MyApi/Access"]
};

//when the spa starts up I login using redirects
msalUserAgent.loginRedirect(requestObj);


//then before calling an api I request a token using this method
 acquireTokenSilent() {
    var promise = msalUserAgent.acquireTokenSilent(requestObj);
    return promise;
  },


Try specifying the scopes as scopes: ["User.Read"] in the acquireTokenSilent() function. Since an access token is only valid for one API. If you need two, call acquireTokenSilent twice with different scopes.

It's okay to specify scopes for two APIs when signing in, but not when getting tokens. A token has an audience that specifies the target API. So you can't use a token for one API against another. And that's why it's only valid for one API.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM