I have an application written with C#
on the top on ASP.NET Core 2.2 framework.
I want to be able to check if a user has a claim before I allow them access to the action.
I created an AuthorizationHandler
to check if the user has the claim like so
public class ClaimExistanceHandler : AuthorizationHandler<MustHaveClaimRequirement>
{
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, MustHaveClaimRequirement requirement)
{
if (context == null
|| context.User == null
|| context.User.Identity == null
|| !context.User.Identity.IsAuthenticated
|| requirement == null
|| string.IsNullOrWhiteSpace(requirement.Type)
|| context.User.HasClaim(requirement.Type, requirement.Value))
{
context.Fail();
}
else
{
context.Succeed(requirement);
}
await Task.Yield();
}
}
}
then the requirement is as follow
public class MustHaveClaimRequirement : IAuthorizationRequirement
{
public string Type { get; set; }
public string Value { get; set; }
public MustHaveClaimRequirement(string type, string value)
{
Type = type;
Value = value;
}
}
But how can I call this requirement as an attribute? For example HasPermission("do something", "1")
It seems that my HasPermission class needs to implement the AuthorizeAttribute
but not sure how would I call the handler from the attribute.