为什么我的 ClaimsIdentity IsAuthenticated 总是错误的(对于 web api 授权过滤器)? [英] Why is my ClaimsIdentity IsAuthenticated always false (for web api Authorize filter)?

查看:17
本文介绍了为什么我的 ClaimsIdentity IsAuthenticated 总是错误的(对于 web api 授权过滤器)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个 Web API 项目中,我覆盖了正常的身份验证过程来检查令牌.代码如下所示:

In a Web API project I am overriding the normal authentication process to check tokens instead. The code looks something like this:

if ( true ) // validate the token or whatever here
{
    var claims = new List<Claim>();
    claims.Add( new Claim( ClaimTypes.Name, "MyUser" ) );
    claims.Add( new Claim( ClaimTypes.NameIdentifier, "MyUserID" ) );
    claims.Add( new Claim( ClaimTypes.Role, "MyRole" ) );

    var claimsIdentity = new ClaimsIdentity( claims );

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

然后当我将 [Authorize] 属性应用于控制器时,它无法授权.

And then later when I apply the [Authorize] attribute to a controller, it fails to authorize.

调试代码确认了相同的行为:

Debug code confirms the same behavior:

// ALWAYS FALSE!
if ( HttpContext.Current.User.Identity.IsAuthenticated ) {
    // do something
}

为什么即使我已经构建了一个有效的 ClaimsIdentity 并将其分配给线程,它仍然认为用户未通过身份验证?

Why does it think the user is not authenticated even though I've constructed a valid ClaimsIdentity and assigned it to the thread?

推荐答案

问题是由于 .Net 4.5 中的重大更改.正如这篇文章,简单地构造一个声明身份不再使它 IsAuthenticated 返回 true.相反,您需要将一些字符串(无关紧要)传递给构造函数.

The problem is because of a breaking change in .Net 4.5. As explained by this article, simply constructing a claims identity no longer makes it IsAuthenticated return true. Instead, you need to pass some string (doesn't matter what) into the constructor.

所以上面代码中的这一行:

So this line in the above code:

var claimsIdentity = new ClaimsIdentity( claims );

变成这样:

// exact string doesn't matter
var claimsIdentity = new ClaimsIdentity( claims, "CustomApiKeyAuth" );

问题就解决了.更新:请参阅 Leo 的其他回答.确切的 AuthenticationType 值可能重要也可能不重要,具体取决于您在身份验证管道中的其他内容.

And the problem is solved. Update: see other answer from Leo. The exact AuthenticationType value may or may not be important depending on what else you have in your auth pipeline.

更新 2:正如 Robin van der Knaap 在评论中所建议的,System.Security.Claims.AuthenticationTypes 值之一可能是合适的.

Update 2: as suggested by Robin van der Knaap in the comments, one of the System.Security.Claims.AuthenticationTypes values might be appropriate.

var claimsIdentity = new ClaimsIdentity( claims, AuthenticationTypes.Password );

// and elsewhere in your application...
if (User.Identity.AuthenticationType == AuthenticationTypes.Password) {
    // ...
}

这篇关于为什么我的 ClaimsIdentity IsAuthenticated 总是错误的(对于 web api 授权过滤器)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆