为什么我的ClaimsIdentity IsAuthenticated总是假的(用于Web API授权过滤器)? [英] Why is my ClaimsIdentity IsAuthenticated always false (for web api Authorize filter)?
问题描述
在一个Web API项目,我重写了正常的认证过程中,检查令牌来代替。在code看起来是这样的:
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;
}
再后来,当我应用 [授权]
属性控制器,它没有授权。
And then later when I apply the [Authorize]
attribute to a controller, it fails to authorize.
调试code印证了相同的行为:
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重大更改的。正如<一个解释href=\"http://leastprivilege.com/2012/09/24/claimsidentity-isauthenticated-and-authenticationtype-in-net-4-5/\">this文章,只是构建一个声明身份不再使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.
所以,这条线在上面code:
So this line in the above code:
var claimsIdentity = new ClaimsIdentity( claims );
这变为:
// exact string doesn't matter
var claimsIdentity = new ClaimsIdentity( claims, "CustomApiKeyAuth" );
和问题解决。
的我想这Q&安培; A主要是链接文章的重述,但问题是我很难找到,所以我希望通过加入这个,我会让它更多谷歌,能为他人在未来。的
这篇关于为什么我的ClaimsIdentity IsAuthenticated总是假的(用于Web API授权过滤器)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!