我正在尝试为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访问用户名,但是如果添加授权属性,则会出现错误。有什么我想念的吗?

谢谢您的时间。如果需要其他信息,请添加评论。

最佳答案

我做错了几件事。
首先,我需要实现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;

    }

}

关于c# - 身份验证筛选器无法与Web API中的授权筛选器一起使用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55394001/

10-09 08:19