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.
Debug code confirms the same behavior:
// ALWAYS FALSE!
if ( HttpContext.Current.User.Identity.IsAuthenticated ) {
// do something
}
Why does it think the user is not authenticated even though I've constructed a valid ClaimsIdentity and assigned it to the thread?