如果不在特定角色属性MVC 5中授权

时间:2016-10-18 09:21:02

标签: attributes authorization asp.net-mvc-5

我需要授权属性才能允许除特定角色以外的所有操作。

之类的东西
    [!Authorize(Roles = "SuperUser")]
    public ActionResult PaySuperUser.....

内置任何东西? 或者对自定义属性的任何建议?

1 个答案:

答案 0 :(得分:1)

我认为自定义属性是一种方法。

这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;

namespace YourFancyNamespace
{
    public class AuthorizeExtended : AuthorizeAttribute
    {
        private string _notInRoles;
        private List<string> _notInRolesList;

        public string NotInRoles
        {
            get
            {
                return _notInRoles ?? string.Empty;
            }
            set
            {
                _notInRoles = value;
                if (!string.IsNullOrWhiteSpace(_notInRoles))
                {
                    _notInRolesList = _notInRoles
                        .Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries)
                        .Select(r => r.Trim()).ToList();
                }
            }
        }

        public override void OnAuthorization(HttpActionContext actionContext)
        {
            base.OnAuthorization(actionContext);
            if (_notInRolesList != null && _notInRolesList.Count > 0)
            {
                foreach (var role in _notInRolesList)
                {
                    if (actionContext.RequestContext.Principal.IsInRole(role))
                    {
                        actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
                    }
                }
            }
        }
    }
}

以下是您可以使用它的方法:

// AuthorizeExtended等于授权(使用角色过滤器)+排除所有讨厌的用户

[AuthorizeExtended(Roles = "User", NotInRoles="PeskyUser")]
[HttpPost]
[Route("api/Important/DoNotForgetToUpvote")]
public async Task<IHttpActionResult> DoNotForgetToUpvote()
{
    return Ok("I did it!");
}

//БProteceExtended等于普通授权+排除所有讨厌的用户

[AuthorizeExtended(NotInRoles="PeskyUser")]
[HttpPost]
[Route("api/Important/DoNotForgetToUpvote")]
public async Task<IHttpActionResult> DoNotForgetToUpvote()
{
    return Ok("I did it!");
}

//ВAntivizeExtended等于授权

[AuthorizeExtended]
[HttpPost]
[Route("api/Important/DoNotForgetToUpvote")]
public async Task<IHttpActionResult> DoNotForgetToUpvote()
{
    return Ok("I did it!");
}