获取AuthorizeAttribute以在webapi2应用程序中使用具有开始日期和到期日期的角色



我需要使用Identity 2通过添加其他属性来修改web api 2项目中的用户角色:DateTime StartDateDateTime EndDate。这是能够在有限的时间内授予用户角色所必需的。

我需要做什么才能获得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;
}

看起来我需要在HttpActionContext.ControllerContext.RequestContext.Principal中对IPrincipal的实现进行子类化,并以某种方式将其注入生命周期中的某个位置,而不是默认的实现。

我该怎么做?

只需像UserAuthorize一样创建AuthorizeAttribute的自定义实现,您将使用[UserAuthorize(Role="poweruser")]而不是使用[Authorize(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 
    }

最新更新