为什么我的声明身份验证总是假的(对于 web api Authorize filter) ?

在一个 WebAPI 项目中,我改用检查令牌来覆盖正常的身份验证过程。代码如下所示:

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]属性应用到控制器时,它无法进行授权。

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

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

为什么它认为用户没有经过身份验证,即使我已经构造了一个有效的声明身份并将其分配给线程?

39116 次浏览

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) {
// ...
}

While the provided answer has some validity in it, it is not entirely correct. You can't assume that just adding any string will magically work. As stated in one of the comment, this string must match one of the AuthenticationTypes enumeration which in turn must match the one specified in the OWIN authentication/authorization middleware....for example...

public void ConfigureOAuth(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);


OAuthAuthorizationServerOptions serverOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new Microsoft.Owin.PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
AuthenticationType = AuthenticationTypes.Password,
AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
Provider = new AppAuthServerProvider()
};




app.UseOAuthAuthorizationServer(serverOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
{
AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
AuthenticationType = AuthenticationTypes.Password
});
}

However, in the above scenario it wouldn't matter much. But, if you are using more authentication/authorization levels the claims will be associated to the one that matches the same AuthenticationType...another example is when you use cookie authentication...

public void Configuration(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "ApplicationCookie",
LoginPath = new PathString("/auth/login")
});
}

where AuthenticationType describes the name of the cookie, since your app may have obtained other cookies from other providers it is important that you set the AuthenticationType when instantiating the claims in order to associate then to the correct cookie