C
C#14mo ago
Dr_Cox1911

✅ Put `[Authorize("myPolicy")]` behind feature flag

Greetings, I'm currently working on authentication and authorization for an API that is already deployed to a couple of customers. The whole auth process sits behind a feature flag using the MS IFeatureManager, so that the API can be deployed completely without auth and once more downtime is possible from customers side auth shall be activated by enabling this feature. I have pretty much all covered by the feature flag, but I don't know how I can conditionally apply the [Authorize("myPolicy")] on my api endpoints. If the feature is disabled I don't even register any auth related services or middlewares.
7 Replies
Pobiega
Pobiega14mo ago
you can't conditionally apply an attribute, as they are compile time metadata but if as you say the feature is disabled there are no auth middlewares, doesnt it still work?
Dr_Cox1911
Dr_Cox1911OP14mo ago
Unfortunately it doesn't work, as I don't even register any services and middleware if the feature is disabled. I get an exception that the auth metadata is defined but no app.UseAuthorization() call is made.
Pobiega
Pobiega14mo ago
Ah, thats unfortunate. The recommended approach seems to be to make your policies conditional ie,
.AddAuthorization(x =>
{
// _env is of type IHostingEnvironment, which you can inject in
// the ctor of Startup
if (_env.IsDevelopment())
{
x.DefaultPolicy = new AuthorizationPolicyBuilder().Build();
}
});
.AddAuthorization(x =>
{
// _env is of type IHostingEnvironment, which you can inject in
// the ctor of Startup
if (_env.IsDevelopment())
{
x.DefaultPolicy = new AuthorizationPolicyBuilder().Build();
}
});
replace that if with your feature toggle check replacing all your policies with "blank" policies
Dr_Cox1911
Dr_Cox1911OP14mo ago
That doesn't work either unfortunately, I get AuthorizationPolicy must have at least one requirement.
Pobiega
Pobiega14mo ago
x.DefaultPolicy = new AuthorizationPolicyBuilder()
.RequireAssertion(_ => true)
.Build();
x.DefaultPolicy = new AuthorizationPolicyBuilder()
.RequireAssertion(_ => true)
.Build();
there you go 🙂
Dr_Cox1911
Dr_Cox1911OP14mo ago
Thanks! It works! I had to get a custom IAuthorizationPolicyProvider alongside your solution to support Authorize attributes with policies that I don't have defined when the feature is disabled. Works like a charm now
Pobiega
Pobiega14mo ago
👍
Want results from more Discord servers?
Add your server