3
\$\begingroup\$

I want to create a AuthorizeAttribute that gets the current ActionMethod RouteData and searches in a database for a user that has access to this ActionMethod.

I created a UserAccessPermission table:

public class UserAccessPermission
{
    [Key]
  public int  UserAccessPermissionId { get; set; }
    public string ActionMethod { get; set; }
    public string Controller { get; set; }
    public string Area { get; set; }
    public bool HasAccess { get; set; }

    [DisplayName("User ID")]
    [ForeignKey("ApplicationUser")]
    public string Id { get; set; }
    [DisplayName("User")]
    public virtual ApplicationUser ApplicationUser { get; set; }

}

and then link it to the User table:

 public class ApplicationUser : IdentityUser
{
    public ApplicationUser()
    {
        AccessPermissions = new HashSet<UserAccessPermission>();

    }
 some custome field

    //*******************************************************************

    public virtual ICollection<UserAccessPermission> AccessPermissions { get; set; }

 }

so each user has multi ActionMethod that can access it. Then I create my custom AuthorizeAttribute:

  public class DynamicRoleAuthorizeAttribute : AuthorizeAttribute
{
   private readonly UserManager<ApplicationUser> _userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        bool result = false;
        if (httpContext == null)
        {
            throw new ArgumentNullException("httpContext");
        }

        IPrincipal user = httpContext.User;
        if (!user.Identity.IsAuthenticated)
        {
            return false;
        }


        //var rolesProvider = new RoleProvider();
        var routeData = httpContext.Request.RequestContext.RouteData;
        var controller = routeData.GetRequiredString("controller");
        var action = routeData.GetRequiredString("action");
        string area = null;
        var userId = httpContext.User.Identity.GetUserId();
        var _user = _userManager.FindById(userId);

        if (routeData.DataTokens["area"] != null)
        {
            area = routeData.GetRequiredString("area");
            result = _user.AccessPermissions.Where(x => x.Controller.Equals(controller) && x.ActionMethod.Equals(action) && x.Area.Equals(area)).Select(x => x.HasAccess).FirstOrDefault();

        }
        else
        {
            result = _user.AccessPermissions.Where(x => x.Controller.Equals(controller) && x.ActionMethod.Equals(action)).Select(x => x.HasAccess).FirstOrDefault();

        }


        if (result)
        {
            return true;
        }

        return false;
        //return base.AuthorizeCore(httpContext);
    }
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result = new HttpUnauthorizedResult();
    }
}  

But this approach is too hard for page management and the admin should give user access permission for each ActionMethod. Is there any better way to do this?

\$\endgroup\$
  • \$\begingroup\$ Designing appropriate authorization usually requires a lot more information analysis than can be offered in a Code Review question. We know nothing of the building blocks of your application, required access levels or required granularity of the authorization. I really wouldn't know where to start. "Too broad" if you ask me. \$\endgroup\$ – Gert Arnold May 20 '18 at 19:33
  • \$\begingroup\$ A good start could be to look at industry standards, for example claims and scopes as implemented by IdentityServer. \$\endgroup\$ – Gert Arnold May 20 '18 at 19:35
  • \$\begingroup\$ @GertArnold what do you mean by 'building blocks of your application'?? \$\endgroup\$ – AminM May 20 '18 at 20:58
  • \$\begingroup\$ AKA aggregates: distinct parts of the application, some of which may require fine-grained authorization, some may be authorizable as a whole or are authorization-free, etc. \$\endgroup\$ – Gert Arnold May 22 '18 at 6:56
  • \$\begingroup\$ @GertArnold what should i do know? \$\endgroup\$ – AminM May 24 '18 at 15:47
2
\$\begingroup\$

Yes. You are close, man!

You have to make relashionships between pairs of controller+action to some user actions.

For example: Security Staff can only view Personal Info: - View Personal

Then your HHRR Manager can: - View Personal - Add Personal - Edit Personal

And finally HHRR Director he can do more actions like:

  • View Personal
  • Add Personal
  • Edit Personal
  • Delete Personl

And now in game you should include some extra tables, bro! hehehehehehe

Lets say your system has HHRR module. Add this module record to the AccessModule table. Then add 3 records to AccessModuleActions like

  • HHRR Director
  • HHRR Manager
  • Security Staff

Apply ACL to each user via PersonalModuleActions table. Acctually you should use PersonalModuleActions at website admin GUI area.

And internally (no GUI for it) you will gonna use WebSiteAccessModuleActions table where you keep relashionships between controller methods and those "roles".

This approach allows use

1) Ignore methods that are not described in WebSiteAccessModuleActions

2) Build very flexible ACL subsystem.

As you see we manipulate kinda of groups of controller methods represented in a user friendly manner

- HHRR Director
- HHRR Manager
- Security Staff

So when I said you are close it is just implement one more level of abstraction.

Enjoy, dude!

enter image description here

P.S. Include Area columnto the WebSiteAccessModuleActions if you have identical controller in several website's areas.

\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.