'Adding both WebApi and WebApp authentication
I have a Web API for which I want controllers to use Bearer token authentication. At the same time I want the Swagger UI to be protected by OIDC.
Scenario:
- Use policy
"Bearer"for[Authorize]on controllers - Use policy
"OpenIdConnect"for Swagger UI (note: the UI, not the requests done in the UI)
I have created a minimal Web API project from the template, and added authentication:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddMicrosoftIdentityWebApiAuthentication(builder.Configuration);
builder.Services.AddMicrosoftIdentityWebAppAuthentication(builder.Configuration);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddAuthorization(options =>
{
// Need this for [Authorize] on controllers to use bearer token for authentication
options.DefaultPolicy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser()
.Build();
});
var app = builder.Build();
app.UseAuthentication();
app.Use(async (context, next) =>
{
if (context.Request.Path.StartsWithSegments("/swagger") && !(context.User.Identity?.IsAuthenticated ?? false))
{
await context.ChallengeAsync(OpenIdConnectDefaults.AuthenticationScheme);
}
else
{
await next();
}
});
app.UseAuthorization();
app.UseSwagger();
app.UseSwaggerUI();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Documentation and another issue says the call order of AddMicrosoftIdentityWebApiAuthentication and AddMicrosoftIdentityWebAppAuthentication doesn't matter. I need to set a default authorization policy though, so controllers with the [Authorize] attribute will accept the "Bearer" policy.
This code seems to work, but what makes me unsure about this is that if I switch the order of AddMicrosoftIdentityWebApiAuthentication and AddMicrosoftIdentityWebAppAuthentication, the Swagger login redirect will create an infinite loop:
builder.Services.AddMicrosoftIdentityWebAppAuthentication(builder.Configuration);
builder.Services.AddMicrosoftIdentityWebApiAuthentication(builder.Configuration);
Here is a repo with a minimal reproducible example: https://github.com/kristofferjalen/MultipleAuth
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
