【问题标题】:ASP.Net MVC:How to attach claim permission to action like rolesASP.Net MVC:如何将声明权限附加到角色等操作
【发布时间】:2016-09-21 21:00:11
【问题描述】:

阅读关于角色和身份声明的文章,还有很多事情没有弄清楚。非常想知道当我们将身份与声明一起使用时如何实现用户访问权限。

当我们使用角色时,我们使用单个或多个角色名称来装饰动作。如果用户具有该角色,则用户可以访问该操作,否则与下面的代码不同。

[AuthLog(Roles = "Manager")]
public ActionResult Create()
{
    var Product = new ProductMaster();
    return View(Product);
}

我想当我们处理身份和声明时,必须有某种方式将角色或权限附加到每个动作,如角色。如果存在这样的东西,那么请分享如何用好的示例代码实现它的想法或提供文章链接。谢谢

【问题讨论】:

  • 当您使用带有声明的令牌(例如 oAuth)时,该令牌将有一个名为“角色”的声明。当您的站点收到此令牌时,它将负责创建一个 Principal 对象并根据 Roles 声明中的角色设置角色。然后您就可以继续使用标准的AuthorizeAttribute 或您的自定义AuthLogAttribute
  • 我在这方面的知识很少。你能把我重定向到任何详细讨论和指导的文章吗?谢谢

标签: asp.net-mvc asp.net-identity claims-based-identity


【解决方案1】:

这是定制的 Authorize,它检查数据库的权限。 例如,您有 3 个用于权限帐户、客户、配置的布尔值 并且您希望基于它们来限制用户,而不是在 actionresult 上放置以下行

您甚至可以在一个操作上添加两个权限,例如,您有一个方法可以通过 Account 和 Client 权限访问,而不是您可以添加以下行

[PermissionBasedAuthorize("Client, Account")]   

下面这个方法是检查数据库中的布尔值。

public class PermissionBasedAuthorize : AuthorizeAttribute
{
    private List<string> screen { get; set; }

    public PermissionBasedAuthorize(string ScreenNames)
    {
        if (!string.IsNullOrEmpty(ScreenNames))
            screen = ScreenNames.Split(',').ToList();
    }

    public override void OnAuthorization(HttpActionContext actionContext)
    {
        base.OnAuthorization(actionContext);
        var UserId = HttpContext.Current.User.Identity.GetUserId();
        ApplicationContext db = new ApplicationContext();

        var Permissions = db.Permissions.Find(UserId);

        if (screen == null || screen.Count() == 0)
        {
            actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
        }

        bool IsAllowed = false;

        foreach (var item in screen)
            foreach (var property in Permissions.GetType().GetProperties())
            {
                if (property.Name.ToLower().Equals(item.ToLower()))
                {
                    bool Value = (bool)property.GetValue(Permissions, null);
                    if (Value)
                    {
                        IsAllowed = true;
                    }
                    break;
                }
            }

        if (!IsAllowed)
        {
            actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-10
    • 2020-01-14
    • 2017-03-11
    • 2013-06-28
    • 2023-03-19
    • 2022-01-01
    • 2013-08-19
    • 1970-01-01
    相关资源
    最近更新 更多