I'm attempting to setup a custom policy provider in asp.net core. I need to pass in several custom authorization attributes to the provider but struggling with how to do so.
I have it setup to accept one enum array currently and is working fine. However, I would like to add 2 more enum arrays as additional, optional parameters to the authorization attribute.
Attribute as it is now:
[LEMClaimAuthorize(new ELocation[] { ELocation.Indy, ELocation.Columbus })]
Would like for it to work like so:
[LEMClaimAuthorize(new ELocation[] { ELocation.Indy, ELocation.Columbus },
new EEntity[] { EEntity.JobTool })]
LEMClaimAuthorizeAttribute is:
public class LEMClaimAuthorizeAttribute : AuthorizeAttribute
{
const string POLICY_PREFIX = "LEMClaim";
public ELocation[] Locations
{
get
{
if (Enum.TryParse(typeof(ELocation[]), Policy.Substring(POLICY_PREFIX.Length), out var locations) )
{
return (ELocation[]) locations;
}
return default(ELocation[]);
}
set
{
int[] intVals = Array.ConvertAll(value, val => (int)val);
string arrayVal = string.Join(",", intVals);
Policy = $"{POLICY_PREFIX}{arrayVal}";
}
}
//remaining code omitted for brevity
}
Custom Authorization Policy Provider:
public class LEMClaimPolicyProvider : IAuthorizationPolicyProvider
{
const string POLICY_PREFIX = "LEMClaim";
public DefaultAuthorizationPolicyProvider FallbackPolicyProvider { get; }
public LEMClaimPolicyProvider(IOptions<AuthorizationOptions> options)
{
FallbackPolicyProvider = new DefaultAuthorizationPolicyProvider(options);
}
public Task<AuthorizationPolicy> GetDefaultPolicyAsync() => FallbackPolicyProvider.GetDefaultPolicyAsync();
public Task<AuthorizationPolicy> GetPolicyAsync(string policyName)
{
if (!policyName.StartsWith(POLICY_PREFIX, StringComparison.OrdinalIgnoreCase))
return FallbackPolicyProvider.GetPolicyAsync(policyName);
string val = policyName.Substring(POLICY_PREFIX.Length);
//CONVERT STRING TO INT[]
int[] ia = val.Split(',').Select(n => Convert.ToInt32(n)).ToArray();
ELocation[] locations = (ELocation[])(object)ia;
var policy = new AuthorizationPolicyBuilder();
policy.AddRequirements(new LEMClaimRequirement(locations));
return Task.FromResult(policy.Build());
}
}
- This IS working for one enum array only.
- How do I get it to work with other enum array parameters?
- If there is a better way, in general, I'm all ears
Thank you for your help!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…