Custom Authorization (Restriction)

Viewed 99

I want to create a custom authorization that takes BranchId, StaffId and RoleId. The Staff can only be allowed to view only his branch when logging in to the application because the branchId is part of the added staff url.

I managed to get the id from the url and passed to string, but I can't figure out how to use this id to check the branch id of the current user and then check to see if the staff should be on the branch and what role before allowing access.

Here is my example. I am new in .net. How can I do such method?

protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                     RestrictViewRequirement requirement)
{
    int? branchId = null;     
    if (context.Resource is AuthorizationFilterContext authContext)
    {
        var tmp = authContext.HttpContext.Request.Query["branchId"].ToString();

        if (!string.IsNullOrEmpty(tmp))
        {
            branchId = int.Parse(tmp);
        }
    }
}
2 Answers

You can add the user's branch id as Claim and then check it against the branch id you are getting from the URL.

You can add the User's Branch id as Claim in the GenerateUserIdentityAsync function

// Add custom user claims here
userIdentity.AddClaim(new Claim("BranchId", "XYZ"));
return userIdentity;

Now when you want to check it, You can get the branch id from the claim. You can get the Claim back like this:

var ci = (ClaimsIdentity)HttpContext.Current.User.Identity;
var branchid = ci.Claims.FirstOrDefault(t => t.Type == "BranchId")?.Value;

If you are logging with Identity SignInManager, you can Dependency Injection the UserManager into the CustomAuthorizationHandler, and then you can get the current login User.

public class CustomAuthorizationHandler : AuthorizationHandler<RestrictViewRequirement>
{
    private readonly UserManager<IdentityUser> _userManager;

    public CustomAuthorizationHandler(UserManager<IdentityUser> userManager)
    {
        _userManager = userManager;
    }

    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, RestrictViewRequirement requirement)
    {
        var currentUser = _userManager.Users.FirstOrDefault();
        //....
        return Task.CompletedTask;
    }
}
Related