Assuming that we have the following code (which a rather extensive specification of the access conditions) I wanted to refactor it. There's a bunch of such policies very similar to each other, with only a tiny variation in a special claim.
services.AddAuthorization(options =>
{
options.AddPolicy("ExtensivePolicy_A",
config => config.RequireClaim("special_claim", "dedicated_value_to_A")
.RequireClaim("claim1", "value1") ...
);
...
options.AddPolicy("ExtensivePolicy_Z",
config => config.RequireClaim("special_claim", "dedicated_value_to_Z")
.RequireClaim("claim1", "value1") ...
);
}
The attempt based on e.g. this, gave me this.
services.AddAuthorization(options =>
{
options.AddPolicy("ExtensivePolicy_A", ConfigPolicyA);
...
options.AddPolicy("ExtensivePolicy_Z", ConfigPolicyZ);
}
private static void ConfigPolicyA(AuthorizationPolicyBuilder builder) { ... }
...
private static void ConfigPolicyZ(AuthorizationPolicyBuilder builder) { ... }
It's much cleaner but still screams parameterization, as the only difference in the config delegates (actions, funcs whatever they call it), is a tiny detail. Optimally, I'd like my privates to look something along the lines of the following.
private static void ConfigPolicy(AuthorizationPolicyBuilder builder, string special) { ... }
And the call to it would pass a parameter.
options.AddPolicy("MarketingPolicy", ConfigPolicy("a"));
However, I can't get it to work. The compiler complains about the action type being wrong. The original intellisense tells me that I'm supposed to pass something of type Action<AuthorizationPolicyBuilder>
, which is kind of against my method's signature (being void
). However, it seems to compile whereas the version that returns said type gets the compiler whining about error converting method group to AuthorizationPolicy
(which is misleading because that type is a signature of another overloaded method).
My best attempt based on this blog (actions with lambda expression) went as far as this.
private static Action<AuthorizationPolicyBuilder, string> test1
= builder => { ... };
However, trying to introduce the extra string parameter fails miserably.
private static Action<AuthorizationPolicyBuilder, string> test2
= (builder, special) => { ... };
What should I google for to get relevant examples, which I'm sure there are a gazillion of out there? I've found examples on generics and methods as paameters but nothing that tipped me over to aha-side.