1

我需要使用 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;
}

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

我该怎么做呢?

4

1 回答 1

1

只需创建AuthorizeAttributelike的自定义实现,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 
    }
于 2015-04-06T12:02:17.030 回答