microsoft-identity-web icon indicating copy to clipboard operation
microsoft-identity-web copied to clipboard

Adding both WebApi and WebApp authentication

Open kristofferjalen opened this issue 2 years ago • 0 comments

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:

  1. Use policy "Bearer" for [Authorize] on controllers
  2. 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);Dou
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

kristofferjalen avatar Jan 27 '22 10:01 kristofferjalen