2
\$\begingroup\$

In the existing system, we need to rebuild the user's authorization.

The database includes Roles and Rights

Roles were previously used but will be skipped in the new version

All authorization will be based on Rights control

I have prepared an attribute that performs such a task

Controller:

[HasRights(Rights.AddPayer, Rights.DeletePayer)]
[HttpPost]
public IActionResult AddPayer([FromBody]PayerModel model)
{
}

Attribute:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = false)]
public class HasRightsAttribute : AuthorizeAttribute, IAuthorizationFilter
{
    HashSet<Rights> userRights;

    public HasRightsAttribute(params Rights[] rights)
    {
        userRights = rights.ToHashSet();
    }

    public void OnAuthorization(AuthorizationFilterContext context)
    {
        Claim claim = context.HttpContext.User.Claims.FirstOrDefault();
        int userId = int.Parse(claim.Value);

        List<int> rights;

        using (var myContext = new myDB())
        {
            rights = (from UR in myContext.TblUserRole
                      join RR in myContext.TblRoleRight on UR.RoleID equals RR.RoleID
                      where UR.UserID == userId
                      select RR.RightID)
                      .ToList();
        }

        var permission = rights.Any(x => userRights.Contains((Rights)Enum.ToObject(typeof(Rights), x)));

        if (!permission)
        {
            //context.Result = new ForbidResult();
            Debug.WriteLine("NO ACCESS");
        }
        else
        {
            Debug.WriteLine("YOU HAVE ACCESS");
        }
    }
}

Is this a good direction?

What can be corrected / changed?

\$\endgroup\$
  • \$\begingroup\$ I would implement this attribute as a factory, see Custom Filter Factories on Dependency Injection in action filters in ASP.NET Core so that you can also inject your repository. \$\endgroup\$ – t3chb0t Jul 8 at 10:00
  • \$\begingroup\$ Correct me if I'm wrong, but this looks like it's going to query the database to check for their permissions on every single request. It might be a better idea to store their rights in their session or signed token instead. \$\endgroup\$ – Rob Jul 11 at 1:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.