2016-10-18 3 views
0

Мне нужен атрибут авторизации для действия, который допускает все, кроме конкретной роли. что-то вродеАвторизовать, если нет в определенном атрибуте роли MVC 5

[!Authorize(Roles = "SuperUser")] 
    public ActionResult PaySuperUser..... 

Все, что построено? Или любое предложение для пользовательского атрибута?

ответ

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 равен Авторизовать (с Role фильтром) + исключающего все досадных пользователей

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

// Б АвторизацияРекомендуемые равноценные Авторизованные + исключить всех противных пользователей

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

// В AuthorizeExtended равна Авторизовать

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