asp.net-mvc-4 - ASP.NET MVC 4具有权限代码的自定义授权属性(不含角色)





authorization custom-attributes (3)


我可以用自定义属性来做到这一点,如下所示。

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

自定义属性类如下。

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

        return privilegeLevels.Contains(this.AccessLevel);           
    }
}

您可以通过重写HandleUnauthorizedRequest方法来重定向您的自定义AuthorisationAttribute的未授权用户:

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

我需要在我的MVC 4应用程序中根据用户权限级别(没有角色,仅限分配给用户的CRUD操作级别的权限级别)控制对视图的访问。

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

[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();
}

这可能吗? 怎么样? 提前致谢...

Chatura




这是对prev的修改。 回答。 主要区别在于用户未通过身份验证时,它使用原始的“HandleUnauthorizedRequest”方法重定向到登录页面:

   protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {

        if (filterContext.HttpContext.User.Identity.IsAuthenticated) {

            filterContext.Result = new RedirectToRouteResult(
                        new RouteValueDictionary(
                            new
                            {
                                controller = "Account",
                                action = "Unauthorised"
                            })
                        );
        }
        else
        {
             base.HandleUnauthorizedRequest(filterContext);
        }
    }



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using SISWEBBSI.Models.Model;
using SISWEBBSI.Models.Model.Entities;
using SISWEBBSI.Models.ViewModel;

namespace SISWEBBSI.Controllers.ActionFilter
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
    public sealed class RequerAutorizacao : ActionFilterAttribute
    {
        public Grupo.Papeis[] Papeis = {} ;
        public string ViewName { get; set; }
        public ViewDataDictionary ViewDataDictionary { get; set; }
        public AcessoNegadoViewModel AcessoNegadoViewModel { get; set; }

        public override void OnActionExecuting(ActionExecutingContext FilterContext)
        {
            if (!FilterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                string UrlSucesso = FilterContext.HttpContext.Request.Url.AbsolutePath;
                string UrlRedirecionar = string.Format("?ReturnUrl={0}", UrlSucesso);
                string UrlLogin = FormsAuthentication.LoginUrl + UrlRedirecionar;
                FilterContext.HttpContext.Response.Redirect(UrlLogin, true);
            }
            else
            {
                if (Papeis.Length > 0)
                {
                    //Papel ADMINISTRADOR sempre terá acesso quando alguma restrição de papeis for colocada.
                    int NovoTamanho = Papeis.Count() + 1;
                    Array.Resize(ref Papeis, NovoTamanho);
                    Papeis[NovoTamanho - 1] = Grupo.Papeis.ADMINISTRADOR;
                    UsuarioModel Model = new UsuarioModel();
                    if (!Model.UsuarioExecutaPapel(FilterContext.HttpContext.User.Identity.Name, Papeis))
                    {
                        ViewName = "AcessoNegado";
                        String Mensagem = "Você não possui privilégios suficientes para essa operação. Você deve estar nos grupos que possuem";
                        if(Papeis.Length == 1)
                        {
                            Mensagem = Mensagem + " o papel: <BR/>";
                        }
                        else if (Papeis.Length > 1)
                        {
                            Mensagem = Mensagem + " os papéis: <BR/>";
                        }

                        foreach (var papel in Papeis)
                        {
                            Mensagem = Mensagem + papel.ToString() + "<br/>";
                        }
                        AcessoNegadoViewModel = new AcessoNegadoViewModel();
                        AcessoNegadoViewModel.Mensagem = Mensagem;
                        ViewDataDictionary = new ViewDataDictionary(AcessoNegadoViewModel);
                        FilterContext.Result = new ViewResult { ViewName = ViewName, ViewData = ViewDataDictionary };
                        return;
                    }
                }
            }
        }
    }
}




asp.net-mvc-4 authorization custom-attributes