ASP.NET MVC 4自定义授权许可codeS属性(无角色) [英] ASP.NET MVC 4 Custom Authorize Attribute with Permission Codes (without roles)

查看:139
本文介绍了ASP.NET MVC 4自定义授权许可codeS属性(无角色)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要控制访问基于用户的权限级别(没有的角色,只为分配给用户的CRUD操作水平特权级别)在我的MVC应用4的观点。

I need to control the access to views based on users privilege levels (there are no roles, only privilege levels for CRUD operation levels assigned to users) in my MVC 4 application.

举例如下AuthorizeUser将是我的自定义属性ABD我需要使用它像下面。

Example as below AuthorizeUser will be my custom attribute abd I need to use it like below.

[AuthorizeUser(AccessLevels="Read Invoice, Update Invoice")]
public ActionResult UpdateInvoice(int invoiceId)
{
   // some code...
   return View();
}


[AuthorizeUser(AccessLevels="Create Invoice")]
public ActionResult CreateNewInvoice()
{
  // some code...
  return View();
}


[AuthorizeUser(AccessLevels="Delete Invoice")]
public ActionResult DeleteInvoice(int invoiceId)
{
  // some code...
  return View();
}

这是可能的吗?怎么样?在此先感谢...

Is this possible to do? How? Thanks in advance...

Chatura

推荐答案

我可以用一个自定义属性如下做到这一点。

I could do this with a custom attribute as follows.

[AuthorizeUser(AccessLevel = "Create")]
public ActionResult CreateNewInvoice()
{
    //...
    return View();
}

自定义属性类,如下所示。

Custom Attribute class as follows.

public class AuthorizeUserAttribute : AuthorizeAttribute
{
    // Custom property
    public string AccessLevel { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = base.AuthorizeCore(httpContext);
        if (!isAuthorized)
        {                
            return false;
        }

        string privilegeLevels = string.Join("", GetUserRights(httpContext.User.Identity.Name.ToString())); // Call another method to get rights of the user from DB

        if (privilegeLevels.Contains(this.AccessLevel))
        {
            return true;
        }
        else
        {
            return false;
        }            
    }
}

您可以在您的自定义未经授权的用户重定向 AuthorisationAttribute 通过覆盖 HandleUnauthorizedRequest 方法:

You can redirect an unauthorised user in your custom AuthorisationAttribute by overriding the HandleUnauthorizedRequest method:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
    filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary(
                    new
                        { 
                            controller = "Error", 
                            action = "Unauthorised" 
                        })
                );
}

这篇关于ASP.NET MVC 4自定义授权许可codeS属性(无角色)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆