0

I am trying to use MSAL library by Microsoft in my react js project. We have done the app registration for both front-end(react js) and backend(api). Currently, I am testing this in my local machine and the api is hosted on an on-premise server. My flow looks like this-

  1. SSO login using MSAL
  2. Use the token received in login process to call the API.

The login works fine, and I’m able to use my Microsoft account to do the SSO login. The problem is when I pass the token(received during login process) to call my api, I get 401 error code – enter image description here

Below is my code - authConfig.js –

const config = {
    auth: {
        clientId: "my-front-end-client-id",
        authority: "https://login.microsoftonline.com/my-tenant-id", 
        redirectUri: "http://localhost:3000/home", 
    },
    cache: {
        cacheLocation: "localStorage"
        storeAuthStateInCookie: false 
    },
    system: {
        loggerOptions: {
            loggerCallback: (level, message, containsPii) => {
                if (containsPii) {
                    return;
                }
                switch (level) {
                    case LogLevel.Error:
                        console.error(message);
                        return;
                    case LogLevel.Info:
                        console.info(message);
                        return;
                    case LogLevel.Verbose:
                        console.debug(message);
                        return;
                    case LogLevel.Warning:
                        console.warn(message);
                        return;
                }
            },
            piiLoggingEnabled: false 
        }
    }
};

const loginRequest = {
    scopes: ["user.read"] 
};

export { config, loginRequest };

Login.js –

  const handleLogin = async () => {
    try {
      await instance.loginPopup(loginRequest);
      navigate("/home");
    } catch (error) {
      console.error("Error logging in:", error);
    }
  };

LandingPage.js (home) –

const { instance, accounts } = useMsal();
const [accessToken, setAccessToken] = useState(null);
    var request = {
        scopes : ['api://backend-client-id/myapp.information.read']
    }

    useEffect(() => {
        const getToken = async () => {
            try {
                const response = await instance.acquireTokenSilent({
                    request,
                    account: accounts[0]

                });

                setAccessToken(response.accessToken);
                console.dir(response);
            } catch (error) {
                console.error(error);
            }
        };

        getToken();
    }, [instance, accounts]);
    

    const handleCallApi = async () => {
        try {
            if (accessToken) {
                const apiResponse = await callApi(accessToken);
                console.log(apiResponse);
            } else {
                console.error("Access token not available");
            }
        } catch (error) {
            console.error("Error calling API:", error);
        }
    };

Azure App registration settings –

  1. Front end app registration – a. Authentication – defined my redirect URIS - http://localhost:3000/home and http://localhost:3000/ b. API permission – enter image description here

  2. Backend(API) app registration – a. Authentication – web redirect URI - http://localhost:3000/home . Access tokens and ID token are selected under implicit grant & hybrid flows. b. API permission - enter image description here c. Expose an api – enter image description here Under scopes, it is myapp.information.readall Under client id, we have given our front-end client id. d. App roles – enter image description here

Under value, it is myapp.information.read

I am fairly new to the authentication process and stuck on this problem for quite some time now.

I tried making several changes in the app registration of Azure as I didn't find anything wrong with the react js code.

1 Answer 1

0

Your scope is wrong. It needs to be exactly User.Read

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