2015-04-01 49 views
0

我需要通过添加其他属性来修改我的web api 2项目中的用户角色:DateTime StartDateDateTime EndDate。这需要能够在有限的时间内授予用户角色。获取AuthorizeAttribute在web api 2应用程序中启动和过期日期的工作角色?

我需要做些什么才能获得Authorize属性,如[Authorize(Role="poweruser")]等,以了解角色日期?

据源(https://github.com/ASP-NET-MVC/aspnetwebstack/blob/master/src/System.Web.Http/AuthorizeAttribute.cs)此过滤器最终调用IPrincipal.IsInRole

protected virtual bool IsAuthorized(HttpActionContext actionContext) 
{ 
    ... 

    if (_rolesSplit.Length > 0 && !_rolesSplit.Any(user.IsInRole)) 
    { 
     return false; 
    } 

    return true; 
} 

看起来我需要继承的IPrincipal的实施HttpActionContext.ControllerContext.RequestContext.Principal并以某种方式在生命周期,而不是默认实现地方注入它。

我该怎么做?

回答

1

只需创建AuthorizeAttribute的自定义实现,如UserAuthorize,而不是使用[Authorize(Role="poweruser")],则将使用[UserAuthorize(Role="poweruser")]。 您的UserAuthorize暗示可能如下所示:

public class UserAuthorizeAttribute : AuthorizeAttribute 
{ 
    /// <summary> 
    /// Validate User Request for selected Feature 
    /// </summary> 
    /// <param name="httpContext"></param> 
    /// <returns></returns> 
    protected override bool AuthorizeCore(HttpContextBase httpContext) 
    { 
     var isAuthorized = base.AuthorizeCore(httpContext); 
     if(!isAuthorized) { 
      return false; //User is Not Even Logged In 
     } 
     //Your custom logic here 
    } 
相关问题