skip to Main Content

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.

2

Answers


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

    app.MapGet("/hello", [AllowAnonymous] () => "Hello, World!");
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search