0

I'm following this tutorial to authenticate a react application using MSAL and call my own api using the authentication token: https://github.com/oizhaolei/typescript-msal-sample

I added the following code to make an api call:

import { loginRequest, config } from "../authConfig";
import { msalInstance } from "../index";

export async function callMsGraph() {
    const account = msalInstance.getActiveAccount();
    if (!account) {
        throw Error("No active account! Verify a user has been signed in and setActiveAccount has been called.");
    }

    const response = await msalInstance.acquireTokenSilent({
        ...loginRequest,
        account: account
    });

    const headers = new Headers();
    const bearer = `Bearer ${response.accessToken}`;
    
    headers.append("Authorization", bearer);

    const options = {
        method: "GET",
        headers: headers
    };

    return fetch(config.endpoint, options)
        .then(response => response.json())        
        .catch(error => console.log(error));
}

authConfig.ts

import { Configuration } from "@azure/msal-browser";

// Config object to be passed to Msal on creation
export const msalConfig: Configuration = {
    auth: {
        clientId: "<client-id>",
        authority: "https://login.microsoftonline.com/<tenant-id>",
        redirectUri: "http://localhost:3000/",
        postLogoutRedirectUri: "/"
    }
};

// scopes
export const loginRequest = {
    scopes: ["api://<client-id>/user_impersonation"]
};

// endpoints 
export const config = {
    endpoint: "https://xxx-webapi.azurewebsites.net/api/v1/jobs"
};

On running this, I see 401 unauthorized error. What am I missing?

SPT
  • 139
  • 1
  • 6
user989988
  • 3,006
  • 7
  • 44
  • 91
  • Before calling the api endpoint, can you check the bearer token and decode the details to see claims and provide decoded values here by masking sensitive values – kavyaS Mar 17 '23 at 12:26

2 Answers2

0

After login ,decode the access token https://jwt.ms and see which endpoint is present in issuer (“iss” claim) i.e v1 or v2 and then go to azure ad portal and change the accesstokenacceptedversion if it not according to that endpoint i.e; it must be null or 1 for V1 and 2 for V2.

enter image description here

If it is correct , please make the required scopes are exposed for that api in portal and granted admin consent with api permissions.

enter image description here

In my case i am calling graph api endpoint but received 401 audience invalid error.

enter image description here

As my Aud clailm doesn't match the clientId where my clientId is AppId and Audience is AppIdUri as per decoded claim:

enter image description here

But both must match.

In my case it worked when ClientId is given with api prefix i.e AppIdUrI: api://<clientId> ,

and given proper permissions like User.Read.All openid permissions and granted admin consent .

enter image description here

Got the access token when called token endpoint: https://login.microsoftonline.com/fxxxxx0/oauth2/v2.0/token

client_id:api://b97xxx74876
client_secret:WWxxx.a5P
scope:https://graph.microsoft.com/.default
redirect_uri:https://jwt.ms
grant_type:client_credentials

worked token endpoint

then called my api i.e; graph api in this case with the received token for graph https://graph.microsoft.com/v1.0/users

enter image description here

kavyaS
  • 8,026
  • 1
  • 7
  • 19
  • Thank you! What should I add the redirect uri in my application? I set it as http://localhost:3000 on running locally it worked however After deploying this change, I see 'localhost redfused to connect' error – user989988 Mar 17 '23 at 19:20
  • Try changing the port number ex: , https://localhost:44316 Or You can even try to replace the localhost with your IP address. Also make sure ,no firewall blocking the connection and whatever port you change , make sure same is given in appregistration reply url and in the code. – kavyaS Mar 22 '23 at 03:56
0

Option 1: You have registered the app under Azure AD rather than Azure AD B2C.

You should navigate to Azure AD B2C to register it. If you don't have an B2C tenant, just create it.

Although you can see the app under Azure AD B2C, it doesn't mean you created it here.

An app registered in Azure AD will be shown under Azure AD B2C - App registrations (Preview) as well.

Option 2: You have selected the wrong supported account type option.

You should select Accounts in any organizational directory or any identity provider. (for authenticating users with user flows) when you created it. Otherwise it won't be shown in B2C User Flow.

Check this one out "https://stackoverflow.com/questions/59133312/aadb2c90068-the-provided-application-with-id-is-not-valid-against-this-service"

Option 2: SOLVED FOR ME, changed this from false to true
"oauth2AllowIdTokenImplicitFlow": true,