基于分配的权限函数的授权

时间:2017-09-12 05:56:37

标签: c# sql-server asp.net-mvc web-applications

我有三个表格  我dbo.PermissionFunc的{​​{1}},dbo.Rolesdbo.Permissions

asp.net MVC web application包含项目中的所有函数名称。 dbo.PermissionFunc包含用户角色,例如admin,user,subuser等 dbo.Roles包含来自dbo.Permissions的{​​{1}}和来自RolesId的{​​{1}}。 我想根据dbo.Roles中指定的值提供PermissionFuncId

Image shows the assigning permission to the role

  

有问题的更新:   使用查询来确定当前用户是否拥有权限

dbo.PermissionFunc

提前致谢

5 个答案:

答案 0 :(得分:5)

您可以使用检查其中的角色和权限的逻辑创建custom AuthorizationAttribute,并将其用于需要的操作。

您可以使用mvc.filters执行IAuthorizationFilter来过滤每个请求。在FilterConfig

中注册
filters.Add(new MyAuthorizationAttribute());

答案 1 :(得分:2)

更新为在MVC操作上使用CustomAuthorize属性

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class CustomAuthorize : AuthorizeAttribute
{
    private string _action { get; set; }

    public CustomAuthorize() { }
    public CustomAuthorize(string action) { _action = action; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext.User == null)
            return false;

        if (!httpContext.User.Identity.IsAuthenticated)
            return false;

        // HasPermission function implements looking up by user name and action
        // to see if user has a role that would give them access to this action
        return PermissionChecker.HasPermission(httpContext.User.Identity.Name, _action);
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        // handle unauthorized requests here
        // return 503 error or whatever
    }

}


// example of using custom attribute in MVC controller action
[HttpGet]
[CustomAuthorize("View")]
public ActionResult MyActionActualViewMethodName()
{
    var result = {
        id = 1,
        name = ""
    };
    return Json(result);
}

[HttpDelete]
[CustomAuthorize("Delete")]
public ActionResult MyActionActualDeleteMethodName(int id)
{
    // do delete action
    return Json(true);
}


// static permission checker implementation    
public static class PermissionChecker
{
    static List<GenericIdNameClass> users = new List<GenericIdNameClass>() {
        new GenericIdNameClass { Id = 1, Name = "John" },
        new GenericIdNameClass { Id = 2, Name = "Bob" },
    };

    static List<GenericIdNameClass> roles = new List<GenericIdNameClass>() {
        new GenericIdNameClass { Id = 10, Name = "User" },
        new GenericIdNameClass { Id = 11, Name = "Admin" },
    };

    static List<GenericIdNameClass> actions = new List<GenericIdNameClass>() {
        new GenericIdNameClass { Id = 100, Name = "View" },
        new GenericIdNameClass { Id = 101, Name = "Create/Edit" },
        new GenericIdNameClass { Id = 102, Name = "Delete" },
    };

    static List<GenericEntityRelationClass> roleActionMappings = new List<GenericEntityRelationClass>() {
        new GenericEntityRelationClass{ Id1 = 10, Id2 = 100 },
        new GenericEntityRelationClass{ Id1 = 11, Id2 = 100 },
        new GenericEntityRelationClass{ Id1 = 11, Id2 = 101 },
        new GenericEntityRelationClass{ Id1 = 11, Id2 = 102 },
    };

    // John only has User role, Bob has User and Admin
    static List<GenericEntityRelationClass> userRoleMappings = new List<GenericEntityRelationClass>() {
        new GenericEntityRelationClass{ Id1 = 1, Id2 = 10 },
        new GenericEntityRelationClass{ Id1 = 2, Id2 = 10 },
        new GenericEntityRelationClass{ Id1 = 2, Id2 = 11 },
    };

    public static bool HasPermission(string userName, string actionName)
    {
        var user = users.SingleOrDefault(x => x.Name == userName);
        if (user == null)
            return false;

        var action = actions.SingleOrDefault(x => x.Name == actionName);
        if (action == null)
            return false;

        var userRoles = userRoleMappings.Where(x => x.Id1 == user.Id).Select(x => x.Id2).ToList();

        return roleActionMappings.Any(x => userRoles.Contains(x.Id1) && x.Id2 == action.Id);
    }

    public class GenericIdNameClass
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    public class GenericEntityRelationClass
    {
        public int Id1 { get; set; }
        public int Id2 { get; set; }
    }
}

答案 2 :(得分:1)

Alsamil,

如果您有时间,请阅读Microsoft正在进行的新方式Claims-Based Authorization

如果你有更多时间,我真的推荐你this会议。 Dominick Baier&amp; Brock Allen在安全行业中非常有名,他们解释了如何以与Claims-Based Authorization文章相关的非常好的方式进行授权。如果我没有错,他们就是这种新授权方式背后的思想。

答案 3 :(得分:1)

对上述问题有效的答案如下:

  

AuthorizationController

#region CustomAuthorizationAttribute
public class CustomAuthorizationAttribute : AuthorizeAttribute
{

    private PermissionRepository _permission = new PermissionRepository();
    private PermissionFuncRepository _permissionFun = new PermissionFuncRepository();


    // roles start
    public string IdentityRoles
    {
        get { return _permissionName ?? String.Empty; }
        set
        {
            _permissionName = value;
        }
    }

    private string _permissionName;

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        //do the base class AuthorizeCore first

        if (httpContext.User.Identity.IsAuthenticated)
        {
            string RoleID = FormsAuthentication.Decrypt(httpContext.Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name.Split('|')[1];
            var permisionID = _permissionFun.FindByName(_permissionName);
            if(permisionID != null)
            {
                var permis = _permission.GetPermission().Where(a => a.Perm_PermFuncID == permisionID.PermFunc_ID && a.Perm_RollID.ToString() == RoleID).FirstOrDefault();
                if (permis != null)
                {
                    return true;
                }
            }
        }
        return false;

    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        //if the user is not logged in use the deafult HandleUnauthorizedRequest and redirect to the login page
        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            base.HandleUnauthorizedRequest(filterContext);
        }
        else
        //if the user is logged in but is trying to access a page he/she doesn't have the right for show the access denied page
        {
            filterContext.Result = new RedirectResult("~/Home/AccessDenied");
        }
    }


}
#endregion
  

Foreach ActionController,我按如下方式访问了这些授权:

    [CustomAuthorization(IdentityRoles = "AdjustmentsView")]
    public ActionResult AdjustmentIndex()
    {
        var adjlist = _Adj.GetAdjustmentHead();
        List<AdjustmentHeadViewModel> adjustlist = new List<AdjustmentHeadViewModel>();
        foreach (var item in adjlist)
        {
            Mapper.Initialize(cfg => cfg.CreateMap<AdjustmentHead, AdjustmentHeadViewModel>());
            AdjustmentHeadViewModel entity = Mapper.Map<AdjustmentHead, AdjustmentHeadViewModel>(item);
            adjustlist.Add(entity);
        }
        return View(adjustlist);
    }

答案 4 :(得分:0)

您需要创建自定义AuthorizeAttribute并使用它标记您的操作。

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class RequireFunction : AuthorizeAttribute
{
    private string _function;

    public RequireFunction(string func) { _function = func; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext.User == null)
            return false;

        if (!httpContext.User.Identity.IsAuthenticated)
            return false;

        // modified code sample from question
        string mail = httpContext.User.Identity.Name;
        var user = _user.GetUserByMail(mail);
        var permFunc = _permissionfunc.FindByName(_function);
        var permission = _permission.checkIfPermitted(Convert.ToInt64(usr.Usr_Role_ID), permFunc.PermFunc_ID);
        return permission != null;
    }
}