2016-11-29 3 views
2

Я создал специальный авторизованный атрибут, отвечающий за проверку того, имеет ли пользователь доступ к данному ресурсу. Для того, чтобы сделать его универсальным, мне нужно две переменные, передаваемые в атрибут:Передача параметра маршрута в пользовательский атрибут

  1. Запрашиваемый тип ресурса
  2. запрашиваемый ресурс ID

Я могу легко сказать, атрибут, который был требуемый тип ресурса , но как передать запрошенный идентификатор в атрибут? Вот мой код, только с последней переменной недостающего (помеченных ?):

[System.Web.Http.Authorize] 
[System.Web.Http.RoutePrefix("api/accounts")] 
public class AccountController : ApiController 
{ 
    [AuthorizeIsOwnResource(ResourcesType = ResourcesTypes.Account, ResourceId = ?)] 
    [System.Web.Http.HttpGet] 
    [System.Web.Http.Route("test/{id}")] 
    public ActionResult Test(string id) 
    { 
     return new HttpStatusCodeResult(HttpStatusCode.OK); 
    } 
} 

Любые предложения? Я предполагаю, что я мог бы удалить параметры атрибута все вместе и определить требуемый тип ресурса и ID из HttpContextBase в AuthorizeCore; но это мой единственный вариант?

+0

У вас есть ответ. Я считаю, что лучшим решением является доступ к именам контроллеров и действий из HttpContextBase. Он чище, проще в реализации и меньше подвержен ошибкам. –

+0

Поразмыслив над проблемой, я думаю, что вы абсолютно правы. Я думаю, что я даже могу извлечь RouteData из HttpContextBase. Я отправлю решение после проверки – MichaelCleverly

ответ

2

Хорошо. Основываясь на комментарии Дугласа Гандини, я решил, что лучший способ - это, вероятно, оставить его в Атрибуте, чтобы решить, какой идентификатор был запрошен. Вот мой работаем пользовательский атрибут:

public class AuthorizeIsOwnResourceAttribute : AuthorizeAttribute 
{ 
    public ResourcesTypes ResourcesType { get; set; } 

    protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext) 
    { 
     var httpContext = HttpContext.Current; 
     var claimsIdentity = httpContext.User.Identity as ClaimsIdentity; 
     var routeData = actionContext.ControllerContext.RequestContext.RouteData; 

     switch (ResourcesType) 
     { 
      case ResourcesTypes.Account: 
       return AuthorizeAccount(routeData, claimsIdentity); 
     } 

     return false; 
    } 

    private bool AuthorizeAccount(IHttpRouteData routedata, ClaimsIdentity claimsIdentity) 
    { 

     var id = routedata.Values["id"].ToString(); 
     var accountClaim = claimsIdentity.Claims.FirstOrDefault(x => x.Type == "Resource-" + ResourcesTypes.Account); 
     if (accountClaim == null || accountClaim.Value != id) 
     { 
      return false; 
     } 

     return true; 
    } 
} 

Короче: я получаю запрошенный идентификатор из actionContext.ControllerContext.RequestContext.RouteData; непосредственно в моем Attribute

0

Вы можете переопределить ActionDescriptor в коде для AuthorizationContext:

// Summary: 
    //  Initializes a new instance of the System.Web.Mvc.AuthorizationContext class using 
    //  the specified controller context and action descriptor. 
    // 
    // Parameters: 
    // controllerContext: 
    //  The context in which the result is executed. The context information includes 
    //  the controller, HTTP content, request context, and route data. 
    // 
    // actionDescriptor: 
    //  An object that provides information about an action method, such as its name, 
    //  controller, parameters, attributes, and filters. 
    public AuthorizationContext(ControllerContext controllerContext, ActionDescriptor actionDescriptor); 


    // Summary: 
    //  Provides information about the action method that is marked by the System.Web.Mvc.AuthorizeAttribute 
    //  attribute, such as its name, controller, parameters, attributes, and filters. 
    // 
    // Returns: 
    //  The action descriptor for the action method that is marked by the System.Web.Mvc.AuthorizeAttribute 
    //  attribute. 
    public virtual ActionDescriptor ActionDescriptor { get; set; } 
    // 
    // Summary: 
    //  Gets or sets the result that is returned by an action method. 
    // 
    // Returns: 
    //  The result that is returned by an action method. 
    public ActionResult Result { get; set; } 
Смежные вопросы