Search code examples
azureasp.net-core-webapitokenmsal-reactmicrosoft-entra-id

Acquire single token for multiple scopes microsoft entra id


I have an asp.net core web api project. This project uses azure entra id for authentication. I have registered 2 apps in this entra one for react client app and second for asp.net core web apis. This web api project has 2 modules one mes which is secured with this scope "api://********-****-****-****-************/Mes" and other user management which required above scope plus these graph api scopes,

 "User.Read",
 "Directory.ReadWrite.All",
 "User.Invite.All"

enter image description here

Now on react app I'm using msal-react and msal-browser for login and attaining token but when i am trying to get a singular token for all these scopes so that I get access to all apis with single token I only get token for either mes scope or graph api scopes

const loginRequest = {
  scopes: [
    "api://********-****-****-****-************/Mes",
    "User.Read",
    "Directory.ReadWrite.All",
    "User.Invite.All",
  ],
};

const handleLogin = async () => {
  try {
    let auth = await instance.loginPopup(loginRequest);
    localStorage.setItem("user", JSON.stringify(auth));
    localStorage.setItem("access_token", auth.accessToken);
    return auth;
  } catch (error) {
    if (error instanceof AuthError && error.errorCode === 'user_cancelled') {
      console.log('User cancelled the login flow');
      return rejectWithValue('User cancelled the login flow');
    } else {
      console.error('Login error:', error);
      throw rejectWithValue(error.message);
    }
  }
};

enter image description here

enter image description here

When I'm requesting all scopes together in login request, its only providing token for graph api, to get token for mes i must request it alone in login request. Purpose of this question is to find a way that let me get single token for all these scopes.


Solution

  • Simple answer is that you can't.

    A token can be acquired for multiple scopes if all those scopes belong to same resource. For example, in a single request you can acquire token for User.Read, Directory.ReadWrite.All and User.Invite.All scopes because they are part of Graph API resource.

    To acquire token for your API, you will need to make a separate request as it is a completely different resource.