Search code examples
azure-active-directorysingle-sign-onmsal-angular

Integration of SSO using MSAL in Angular project gets 401 returned error after login


I am fully following the example from Example for Angular 16 from MSAL Git. The code is exactly the same with the example except for the client ID and authority. When I login with my account I got 401 error response. I also don't know how to decode the encrypted code in URL. Is it because that my account does not have access to the application in Azure AD and how can I decode the URL? The URL is like localhost:5069/api#code=xxx&client_info=xxx&state=xxx&session_state=xxx and contains 4 parts, code, client_info,state and session_state. How can I extract info from them?

401 error


Solution

  • The 401 error usually occurs if the Microsoft Entra ID application is not granted required API permissions to perform the operation.

    I created a Multi-Tenant Microsoft Entra ID application:

    enter image description here

    Registered Redirect URL:

    enter image description here

    Grant User.Read delegated API permission as you are calling /me endpoint:

    enter image description here

    Now in environment file replace your client ID:

    export const environment = {
        production: false,
        msalConfig: {
            auth: {
                clientId: 'YourClientID',
                authority: 'https://login.microsoftonline.com/common'
            }
        },
        apiConfig: {
            scopes: ['user.read'],
            uri: 'https://graph.microsoft.com/v1.0/me'
        }
    };
    

    enter image description here

    When I ran the sample, I logged using Popup:

    enter image description here

    The user logged in successfully:

    enter image description here

    Able to fetch signed in user profile data successfully:

    enter image description here

    To resolve the error, make sure to grant required API permissions to the Microsoft Entra ID application.

    If still the issue persists, check if you are passing valid ClientID.

    • And make sure to pass correct or required scope in the environment file.
    • If you are calling any other API then grant and pass the required scope.

    Reference:

    microsoft-authentication-library-for-js/samples/msal-angular-v3-samples/angular16-sample-app at dev · AzureAD/microsoft-authentication-library-for-js · GitHub