private static void BuildPolicy(AuthorizationPolicyInfo policy, AuthorizationOptions config) { var builder = new AuthorizationPolicyBuilder(); policy.AuthenticationSchemes?.ForEach(builder.AuthenticationSchemes.Add); if (policy.Requirements != null && policy.Requirements.Any()) { foreach (var policyRequirement in policy.Requirements) { switch (policyRequirement.RequirementType) { case AuthorizationRequirementType.ClaimsAuthorizationRequirement: var claimsInfo = JObject.Parse(policyRequirement.Requirement) .ToObject <ClaimsInfo>(); builder.RequireClaim(claimsInfo.ClaimType, claimsInfo.RequiredValues); break; case AuthorizationRequirementType.RolesAuthorizationRequirement: builder.RequireRole(JObject.Parse(policyRequirement.Requirement) .ToObject <string[]>()); break; case AuthorizationRequirementType.NameAuthorizationRequirement: builder.RequireUserName(policyRequirement.Requirement); break; case AuthorizationRequirementType.OperationAuthorizationRequirement: builder.AddRequirements( new OperationAuthorizationRequirement() { Name = policyRequirement.Requirement }); break; case AuthorizationRequirementType.DenyAnonymousAuthorizationRequirement: builder.RequireAuthenticatedUser(); break; case AuthorizationRequirementType.DenyAuthorizationRequirement: builder.AddRequirements(new DenyAuthorizationRequirement()); break; case AuthorizationRequirementType.CustomAuthorizationRequirement: builder.AddRequirements(Activator.CreateInstance(Type.GetType(policyRequirement.Type), JObject.Parse(policyRequirement.Requirement).ToObject <object[]>()) as IAuthorizationRequirement); break; // TODO implement the assertion requirement. //case AuthorizationRequirementType.ClaimsAuthorizationRequirement: // builder.RequireAssertion(handler => {handler.}) // break; } } } config.AddPolicy(policy.Name, builder.Build()); }
public static AuthorizationPolicy ToAuthPolicy(this AuthorizationPolicyInfo info) { var policy = new AuthorizationPolicyBuilder(); var hasAnyRequirements = false; if (info.AllowedRoles.Count > 0) { policy.RequireRole(info.AllowedRoles); hasAnyRequirements = true; } if (info.AuthenticationSchemes.Count > 0) { policy.AuthenticationSchemes = info.AuthenticationSchemes; } if (info.RequireAuthenticatedUser) { policy.RequireAuthenticatedUser(); hasAnyRequirements = true; } if (info.RequiredClaims.Count > 0) { foreach (var c in info.RequiredClaims) { if (c.AllowedValues.Count > 0) { policy.RequireClaim(c.ClaimName, c.AllowedValues); } else { policy.RequireClaim(c.ClaimName); } hasAnyRequirements = true; } } if (!string.IsNullOrWhiteSpace(info.RequiredUserName)) { policy.RequireUserName(info.RequiredUserName); hasAnyRequirements = true; } if (!hasAnyRequirements) { // allow anonymous Func <AuthorizationHandlerContext, bool> allowAny = (AuthorizationHandlerContext authContext) => true; policy.RequireAssertion(allowAny); } return(policy.Build()); }