My API is enforcing a global authorization policy to require authenticated users on all endpoints, unless they explicitly specify another policy or opt out via [AllowAnonymous]
.
This works fine with the guidance of using a Fallback Policy:
builder.Services.AddAuthorization(options =>
{
options.FallbackPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
});
However, now I’m trying to add .NET 8’s new identity endpoints, which seem to use minimal APIs under the hood. Unfortunately, they seem incompatible with the above approach, with calls to the /register
endpoint resulting in infinite login redirects as it must now also be following the default policy.
Is there a way to customise auth for the identity endpoints, e.g. add [AllowAnonymous]
to /register
so it doesn’t follow the global fallback policy?
1
One workaround seems to be changing the fallback policy approach to this:
builder.Services
.AddControllers(config => config.Filters.Add(new AuthorizeFilter()))
Which seems to achieve the following goals:
- Require Authorization by default on all controllers
- Controllers can explicitly opt out via
[AllowAnonymous]
or setting another policy. - The .NET 8.0 identity endpoints continue to seemingly work unbroken.
However, I’m not the biggest fan of this workaround because:
- It doesn’t communicate the intent as clearly as the fallback policy approach.
- I’m not sure if it is supposed to behave in this way, or I just happen to be relying on undocumented behaviour.