Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can .NET 6 minimal API endpoints have opt-out authorization?

Tags:

c#

asp.net

I was trying to code a small API where every endpoint should have auth enabled by default, because I don't want to repeat the same [Authorize] attribute or .RequiresAuthorization() call for every endpoint.

I did all the usual .AddAuthentication(), .AddAuthorization(), .UseAuthentication(), .UseAuthorization(), but no matter how I parameterized these, I couldn't get an Unauthorized response, unless I explicitly put on the attribute.

Since I have more endpoints that require auth than not, I'd prefer to just decorate the open ones with [AllowAnonymous]

I'm not even sure if it can be done with regular Web API/MVC, but I certainly couldn't find anything for the new minimal API approach.

like image 546
romeozor Avatar asked Dec 31 '25 23:12

romeozor


2 Answers

You can set a FallBackPolicy or DefaultPolicy

services.AddAuthorization(options =>
{
    options.FallbackPolicy = new AuthorizationPolicyBuilder()
      .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
      .RequireAuthenticatedUser()
      .Build();
});

and than just use AllowAnonymous on your public apis

like image 80
elvir.dolic Avatar answered Jan 02 '26 11:01

elvir.dolic


You can add the AllowAnonymous attribute to a minimal API endpoint like this:

app.MapGet("/hello", [AllowAnonymous] () => "Hello, World!");
like image 36
DavidG Avatar answered Jan 02 '26 12:01

DavidG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!