I’m trying to implement OAuth2 authentication on my API server written in ASP.NET Core. I have registered my application on Azure and I have the secret, clientId, tenantId, and scope available.
I configured the authentication with the following code in the Program.cs file:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));
I am able to generate the authentication bearer token using Postman.
{
"token_type": "Bearer",
"scope": "api://************/resources",
"expires_in": 3975,
"ext_expires_in": 3975,
"access_token": "fsdfdklfnsldknfslkdnl..."
}
However, I want to configure Swagger to test my APIs. Therefore, I have added the following code:
builder.Services.AddSwaggerGen(options =>
{
options.EnableAnnotations();
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
In = ParameterLocation.Header,
Description = "Please enter token",
Name = "Authorization",
Type = SecuritySchemeType.Http,
BearerFormat = "JWT",
Scheme = "bearer"
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Name = "Bearer",
In = ParameterLocation.Header,
Reference = new OpenApiReference
{
Type=ReferenceType.SecurityScheme,
Id="Bearer"
}
},
Array.Empty<string>()
}
});
});
Any request I try to make through Swagger (after entering the bearer token) results in a 404 error (but I think it’s a redirect from the 401 error).
I am new to ASP.NET Core programming and it’s not clear to me whether the error is in the authentication configuration or in Swagger.