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.
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
You can add the AllowAnonymous attribute to a minimal API endpoint like this:
app.MapGet("/hello", [AllowAnonymous] () => "Hello, World!");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With