Bearer was not authenticated.

Mr Edge 221 Reputation points
2023-04-29T09:03:47.1166667+00:00

Im using this repo as a guide

https://github.com/Azure-Samples/ms-identity-docs-code-dotnet/tree/main/web-api

My code is a .Net 6 Web API Core (.Net 6) project is

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Identity.Web;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));

builder.Services.AddAuthorization(config =>
{
    config.AddPolicy("AuthZPolicy", policyBuilder =>
        policyBuilder.Requirements.Add(new ScopeAuthorizationRequirement() { RequiredScopesConfigurationKey = $"AzureAd:Scopes" }));
});
var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

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

app.MapControllers();

app.Run();

When i run the weatherforecast URL i get a 401 with the error listed under Debug

Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler: Debug: AuthenticationScheme: Bearer was not authenticated.

Microsoft.AspNetCore.Authorization.DefaultAuthorizationService: Information: Authorization failed. These requirements were not met:

ScopeAuthorizationRequirement:Scope=

Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler: Information: AuthenticationScheme: Bearer was challenged.

My json config file

  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "ClientId": "1235456",
    "TenantId": "456788",
    "Scopes": "https://ourDomain.onmicrosoft.com/123456789/"
  }

I tried adding

builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})

Which made no difference, finally i added

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(cfg => {
        cfg.RequireHttpsMetadata = false;
        cfg.SaveToken = true;
        cfg.TokenValidationParameters = new TokenValidationParameters()
        {
            ValidateAudience = false,
            ValidateLifetime = false,
            ValidateIssuerSigningKey = true
        };
    })

but then i got the error the scheme already exists.

What code am i missing or is this related to the app registration setup?

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,564 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,946 questions
Azure App Service
Azure App Service
Azure App Service is a service used to create and deploy scalable, mission-critical web apps.
7,785 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Boris Von Dahle 3,126 Reputation points
    2023-04-29T13:54:10.39+00:00

    Hello,

    I think the issue may be in app registration settings :

    Ensure that In the "Expose an API" section, ensure that you have defined an application scope. The scope's name should match the value specified in your configuration file under "AzureAd:Scopes". For example, if your scope in the configuration is https://ourDomain.onmicrosoft.com/123456789/, you should have a scope defined as https://ourDomain.onmicrosoft.com/123456789/ in the "Expose an API" section of your app registration. Also make sure the client application that calls your Web API is granted the required permissions (delegated permissions) for the defined scope. If you still have issues, let us know more about your client app and how it requests the access token. Good luck!

    And If you find this answer usefull please mark it as accepted to help others with same issue find this topic.

    0 comments No comments

  2. Tiny Wang-MSFT 2,646 Reputation points Microsoft Vendor
    2023-05-01T03:06:49.5433333+00:00

    Hi @Mr Edge , the code sample you used contained a Web API which is protected by Azure AD. If this is what you want to add to your API, then I trust you already know that after integrating the Azure AD, you have to have a correct access token in the request header in your API request like Authorization: Bearer access_token.

    Next, we have to first register an Azure AD application to expose an API and this is what @Boris Von dahle mentioned. Here's the official document about how to expose a scoped API permission. After that we can get an API scope like api://client_id/scope__name. Then we need to add this API permission to the Azure AD app which is used for the authorization (you used to set ClientId in appsetting.json), you can also use the same app which exposing the API.

    User's image

    After adding the API permission, we can change the code like the sample. To call this api, we have to generate an access token now. We can use auth code flow. First to get the auth code via this request, pls note to change the redirect URl you set in AAD Authentication blade.

    https://login.microsoftonline.com/tenant_id/oauth2/v2.0/authorize?
    client_id=aad_client_id
    &response_type=code
    &redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
    &response_mode=query
    &scope=api://aad_client_id_which_exposed_api/permission_name
    &state=12345
    

    Then using the code in the url to generate access token. You can decode the access token and see it contains the scp claim which value is the API permission you exposed and consented.

    User's image

    Finally you can call your API

    User's image

    =============================================

    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best Regards,

    TinyWang


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.