简体   繁体   中英

Asp.net Web API .NET Core 3.1 and Azure AD - system.unauthorizedaccessexception: neither scope or roles claim was found in the bearer token

I am trying to secure my Web Api with Azure AD. This application will be accessed by a console app, and the token will be generated from a client id / secret. I followed the quickstart from https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-v2-aspnet-core-web-api .

After obtaining a client token and sending through the bearer auth header, I am getting an error

System.UnauthorizedAccessException: IDW10201: Neither scope or roles claim was found in the bearer token.

I'm obtaining an access token with this code:

       public static async Task<string> GetAccessToken(string aadInstance, string aadTenant, string aadClientId, string aadClientSecret, string apiResourceId)
    {
        string authority = aadInstance.TrimEnd('/') + "/" + aadTenant;
        var app = ConfidentialClientApplicationBuilder.Create(apiResourceId)
            .WithClientId(aadClientId)
            .WithClientSecret(aadClientSecret)
            .WithAuthority(authority)
            .Build();

        var tokenrequest = app.AcquireTokenForClient(new string[] { "api://resourceid/.default" });
        var tokenresult = await tokenrequest.ExecuteAsync();
        return tokenresult.AccessToken;

    }

My startup code in the web api looks like this:

       public void ConfigureServices(IServiceCollection services)
    {
        JwtSecurityTokenHandler.DefaultMapInboundClaims = false;
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddMicrosoftIdentityWebApi(Configuration);

later in the startup...

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });

        app.UseOpenApi();
        app.UseSwaggerUi3();
    }

在此处输入图片说明

It turns out that the setup in Azure AD was missing a role that needed to be added to the manifest as well as the permissions to the api of the client application, as per step 8 in https://dotnetplaybook.com/secure-a-net-core-api-using-bearer-authentication/

Unfortunately the MS documentation doesn't put this part in the quick start.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM