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 );
Becomes this:
// exact string doesn't matter
var claimsIdentity = new ClaimsIdentity( claims, "CustomApiKeyAuth" );
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.
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) {
// ...
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…