question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Invalid-grant error after upgrading to alpha.3

See original GitHub issue

Library

  • @azure/msal-react@1.0.0-alpha.3

Description

I had a working integration of msal-react with an on-behalf-of flow and an asp.net api with the Alpha.0. After I have upgraded to alpha.3 I am receiving the following error:

InteractionRequiredAuthError: invalid_grant: AADSTS65001: The user or administrator has not consented to use the application with ID '611c5aa6-f7de-4a06-ace7-xxxxxxxxxxx' named 'Demo-Spa'. Send an interactive authorization request for this user and resource.

This is my authConfig:

export const msalConfig = {
    auth: {
        clientId: "611c5aa6-f7de-4a06-ace7-xxxxxxxxxxx",
        authority: "https://login.microsoftonline.com/291d05b0-1020-xxxx-xxxxxxxxxxx",
        redirectUri: process.env.NEXT_PUBLIC_HOSTNAME ?? process.env.HOSTNAME,
        navigateToLoginRequestUrl: false
    },
    cache: {
        cacheLocation: "localStorage", 
        storeAuthStateInCookie: false 
    },
}

export const loginRequest = {
    scopes: ["openid", "profile", "offline_access"]
}

// Add here scopes for access token to be used at the API endpoints.
export const tokenRequest = {
    scopes: [apiConfig.resourceScope]
}

// Add here scopes for silent token request
export const silentRequest = {
    scopes: ["openid", "profile", apiConfig.resourceScope]
}

// Coordinates and required scopes for your web api
export const apiConfig = {
    resourceUri: "https://localhost:5001/api/profile",
    resourceScope: "api://9cb0437e-723f-426c-9d8c-d753e4833b9c/access_as_user"
}

With this being my Api authentication configuration:

protected virtual void ConfigureAuthentication(IServiceCollection services)
{
    IdentityModelEventSource.ShowPII = true;
    services.AddAuthentication(o =>
    {
        o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddMicrosoftIdentityWebApi(this.Configuration)
           .EnableTokenAcquisitionToCallDownstreamApi()
              .AddMicrosoftGraph(this.Configuration.GetSection("DownstreamApi"))
              .AddInMemoryTokenCaches();
    services.AddAuthorization();
}

taken from here: https://github.com/Azure-Samples/ms-identity-javascript-react-spa-dotnetcore-webapi-obo

Logging into the Frontend application works as expected. It is only when I try to access the protected api, that this error pops up.

I have to admit, that I am quiet confused about the concepts being applied here and have several question:

  • What is the resourceUri: "https://localhost:5001/api/profile", referring to? It did not seem to have any effect in alpha.0, as I have never used that endpoint to query data. I am only using https://localhost:5001/weatherforecast
  • Where is the resourceScope: “api://9cb0437e-723f-426c-9d8c-d753e4833b9c/access_as_user” being verified? On AAD or the api? The WeatherForecastController is only decorated with an out of the box [Authorize] attribute

What I am currently doing is the following:

const WeatherComponent = () => {
    const { accounts, instance } = useMsal()
    const account = useAccount(accounts[0] || {})
    const [weather, setWeather] = useState<Weather[]>([])

    useEffect(() => {
        if (account) {
            instance.acquireTokenSilent({
                scopes: ["User.Read", "api://9cb0437e-723f-426c-9d8c-d753e4833b9c/access_as_user"],
                account,
            }).then(async (res) => {
                if (res) {
                    const result = await fetch(`${config.apiUri}/weatherforecast`, {
                        headers: {
                            'Authorization': `Bearer ${res["accessToken"]}`
                        }
                    })
                    const weather: Weather[] = await result.json()
                    setWeather(weather)
                }
            })
        }

    }, [account])

    return (
        <>
            <ul>
                {weather.map((w) => {
                    return <li key={w.date}>{w.summary}</li>
                })}
            </ul>
        </>
    )
}

export default WeatherComponent

I am currently trying any combination of scopes, that comes to my mind, but the only thing that does not come back with a Bad Request error and the error message above is an empty scopes array - which then causes a 401 on the api endpoint.

Right now, I have no idea how to proceed and am gratefl for any help debugging this.

Source

  • Internal (Microsoft)
  • [X ] Customer request

Update: After opening the appliction in incognito mode, the log in worked. Switching back to normal mode, it started working again, too. I will continue investigating this tomorrow, after a good night of sleep.

Update2: The error reappeared, after I cleared localstorage and revoked the consent via https://myapplications.microsoft.com/

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:5

github_iconTop GitHub Comments

1reaction
jo-arroyocommented, Jan 26, 2021

@Servellia It is expected that you would receive an error like this if the user has not consent to the resource scope. If you provide the resource scope in the scopes provided in the login, they will be prompted to consent to the resource scope on login.

export const loginRequest = {
    scopes: ["openid", "profile", apiConfig.resourceScope]
}

// Add here scopes for access token to be used at the API endpoints.
export const tokenRequest = {
    scopes: [apiConfig.resourceScope]
}

// Add here scopes for silent token request
export const silentRequest = {
    scopes: ["openid", "profile", apiConfig.resourceScope]
}
0reactions
Mar-hecommented, Jan 27, 2021

@jo-arroyo Yes, absolutely. You were a great help. Thank you.

Read more comments on GitHub >

github_iconTop Results From Across the Web

EMA: {"error":"invalid_grant" } - Refinitiv Developer Community
The error indicates that you likely do not have valid OAuth grant credentials. When you registered for this service, did you receive a...
Read more >
Google OAuth “invalid_grant” nightmare — and how to fix it
Based on the error description of the OAuth2 spec, the error message would be returned in cases where the tokens were malformed, incomplete...
Read more >
Suddenly getting invalid_grant for refresh_token in production
We have been using the OAuth refresh_token stuff for a few months. Then we noticed our packages are not confirmed to Ebay automatically....
Read more >
How to interpret and resolve the "Invalid Grant" error for ...
This happens when the user that connected the Google Data Source in Databox has their permissions changed or revoked to the Google Account....
Read more >
The custom asset is invalid. Details: Invalid field version value
Details: Invalid field version value: 1.0.0-alpha+001" ... When publishing a new asset version, I am getting an error:
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found