How to apply `[Authorize(AuthenticationSchemes = "Api")]` with Minimal API in ASP.NET Core?

46 views Asked by At

I am trying to to Minimal API in an ASP.NET Core app. I added the following endpoint

app.MapPost("api/content", CallbackAsync);

The defined the CallbackAsync as a static function as the following

[Authorize(AuthenticationSchemes = "Api")]
private static async Task<IResult> CallbackAsync(
    
    IAuthorizationService authorizationService,
    HttpContext httpContext)
{
    // ...

    return Results.Ok(...);
}

Authentication is failing. when I use controller, adding [Authorize(AuthenticationSchemes = "Api")] works but not with Minimal API.

How can I apply [Authorize(AuthenticationSchemes = "Api")] with minimal API?

2

There are 2 answers

0
jepozdemir On

you need to configure authentication middleware explicitly. UseAuthentication() and UseAuthorization() adds required middlewares to the pipeline.

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

// Add authentication middleware
app.UseAuthentication();

// Add authorization middleware
app.UseAuthorization();

app.MapPost("api/content", CallbackAsync);

app.Run();

[Authorize(AuthenticationSchemes = "Api")]
private static async Task<IResult> CallbackAsync(
    IAuthorizationService authorizationService,
    HttpContext httpContext)
{
    // ...

    return Results.Ok(...);
}
1
jaabh On

Similar to a standard controller attribute. In Program.cs file,

builder.Services.AddAuthentication().AddJwtBearer("api");
builder.Services.AddAuthorizationBuilder()
  .AddPolicy("api", policy =>
        policy
            .RequireRole("admin")
            .RequireClaim("scope", "api/content"));

var app = builder.Build();

app.MapPost("api/content", (HttpContext context, 
                           IOtherDependency otherDependency, 
                           CallBackAsyncClass callBackAsyncClass) => 
    callBackAsyncClass.CallBackAsync(otherDependency, context))
    .RequireAuthorization("api");

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

For additional information this link should be helpful.

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/minimal-apis/security?view=aspnetcore-8.0

Ensure that any other dependencies that rely on DI are also injected using

builder.Services.AddScoped<IDependency, Dependency>();

The DI part should remain the same.