在Web API项目中,我重写了正常的身份验证过程以判断令牌.代码如下所示:

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
}

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

推荐答案

问题是因为一个突破性的变化.净4.5.正如this article所解释的,简单地构造一个索赔身份不再意味着它是经过验证的返回.相反,您需要向构造函数传递一些字符串(不管是什么).

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

var claimsIdentity = new ClaimsIdentity( claims );

变成这样:

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

问题解决了.Update:.看看狮子座的其他答案.确切的AuthenticationType值可能重要,也可能不重要,这取决于auth管道中的其他内容.

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

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

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

Asp.net相关问答推荐

有人可以解释一下这个Eager 加载示例吗?

如何在 MVC 中为国家和州/省创建 Select 列表

从 asp.net 中的 Web.config 获取连接字符串

ASP.NET Web 应用程序 (.NET Framework) 与 ASP.NET Core Web 应用程序 (.NET Framework) 之间的差异

返回 HttpResponseMessage 时的 WebAPI Gzip

ASP.NET 中的 <% %>(嵌入式代码块)

如何将枚举类型绑定到 DropDownList?

使用 Asp.Net MVC 和 Web Api 配置 Ninject

如何在 asp net core api 中使用 Created(或 CreatedAtAction / CreatedAtRoute)

如何从 NuGet 安装 EntityFramework 5.0(和其他旧版本)?

如何获得 System.Diagnostics.Process 的输出?

WebForm_PostBackOptions 文档

Windows Azure PaaS(网络角色)的真正替代品?

如何保护存储在 web.config 中的密码?

删除 HTML 或 ASPX 扩展

HttpContext.Current.Request.Url.Host 它返回什么?

ASP.NET 应用程序状态与静态对象

将 MemoryStream 写入响应对象

try 为 Medium Trust 开发是否会失败?

Appdomain 回收究竟是什么