身份验证筛选器无法与Web API中的授权筛选器一起使用

时间:2019-03-28 09:21:01

标签: c# asp.net asp.net-web-api asp.net-web-api-filters

我正在尝试为ASP.NET Web API创建自定义身份验证筛选器。以下是我的身份验证过滤器的代码

public class IDPAuthenticationFilter : AuthorizationFilterAttribute
{
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        var identity = new ClaimsIdentity();
        identity.AddClaim(new Claim(ClaimTypes.Name, "testUser"));
        identity.AddClaim(new Claim(ClaimTypes.Role, "client"));
        identity.AddClaim(new Claim("testUser"));
        identity.AddClaim(new Claim("APP:USERID", "50123"));

        var principal = new GenericPrincipal(identity, new string[] { });
        Thread.CurrentPrincipal = principal;
        HttpContext.Current.User = principal;

        base.OnAuthorization(actionContext);
    }
}

我已全局配置了身份验证过滤器,并使用断点确认了该过滤器正在被调用。

config.Filters.Add(new IDPAuthenticationFilter());

问题是,如果我将[System.Web.Http.Authorize]属性添加到任何控制器,则会出现401未经授权错误。我可以在控制器操作中使用User.Identity.Name访问用户名,但是如果添加授权属性,则会出现错误。我有什么想念的吗?

谢谢您的时间。如果需要其他任何信息,请添加注释。

1 个答案:

答案 0 :(得分:0)

有些事情我做错了。 首先,我需要实现IAuthenticationFilter而不是AuthorizationFilterAttribute

第二种设置身份的方法不正确。以下是对我有用的代码。

public class IDPAuthenticationFilter : Attribute, IAuthenticationFilter 
{

    public bool AllowMultiple => false;

    public async Task AuthenticateAsync (HttpAuthenticationContext context, CancellationToken cancellationToken) 
    {

        HttpRequestMessage request = context.Request;
        AuthenticationHeaderValue authorization = request.Headers.Authorization;

        if (authorization == null) {
            return;
        }
        if (authorization.Scheme != "Bearer") {
            return;
        }

        var claims = new List<Claim> ();
        claims.Add (new Claim (ClaimTypes.Name, "testUser"));
        claims.Add (new Claim (ClaimTypes.Role, "client"));
        claims.Add (new Claim ("sub", "testUser"));
        claims.Add (new Claim("APP:USERID", "50123"));

        var identity = new ClaimsIdentity (claims, "Auth_Key");

        var principal = new ClaimsPrincipal (new [] { identity });
        context.Principal = principal;
        HttpContext.Current.User = context.Principal;
        Thread.CurrentPrincipal = context.Principal;

    }

}