C# ASP.NET WebAPI基本身份验证始终失败,因为401/UNAUTHORD

C# ASP.NET WebAPI基本身份验证始终失败,因为401/UNAUTHORD,c#,authentication,asp.net-web-api,authorization,C#,Authentication,Asp.net Web Api,Authorization,试图使用基本身份验证保护我的ASP.NET Web API-2,但最终总是出现错误: 401/Unauthorized Authorization has been denied for this request. 下面是我的控制器和ajax请求代码片段以及请求和响应头 BasicAuthenticationHandler.SendAsync始终成功运行,直到: return base.SendAsync(request, cancellationToken); 问:那么为什么它最终成为40

试图使用基本身份验证保护我的ASP.NET Web API-2,但最终总是出现错误:

401/Unauthorized
Authorization has been denied for this request.
下面是我的控制器和ajax请求代码片段以及请求和响应头

BasicAuthenticationHandler.SendAsync始终成功运行,直到:

return base.SendAsync(request, cancellationToken);
问:那么为什么它最终成为401/未经授权?

如果我从控制器操作中删除[Authorize],那么它可以工作,但没有任何安全性

注意:因为这是一个跨域请求,所以我在服务器端启用了CORS

我的身份验证处理程序

protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
    var principal = Thread.CurrentPrincipal;
    if (principal.Identity.IsAuthenticated)
    {
        return base.SendAsync(request, cancellationToken);
    }

    var encryptedTicket = ExtractToken(request.Headers.Authorization); // simply returns a string
    if (encryptedTicket != null)
    {
        var ticket = FormsAuthentication.Decrypt(encryptedTicket);
        var serializer = new JavaScriptSerializer();
        var user = serializer.Deserialize<UserInfoModel>(ticket.UserData);

        if (user != null)
        {
            var identity = new GenericIdentity(user.UserName, "Basic");
            Thread.CurrentPrincipal = new GenericPrincipal(identity, new string[0]);
        }
    }

    // Code reaches here always successfully but after this line errors Unauthorized
    return base.SendAsync(request, cancellationToken);
}
public class ProductController : ApiController
{

Product[] products = new Product[] 
{ 
    new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 } 
};

[Authorize]
[Route("test/products")]
[EnableCors(origins: "*", headers: "*", methods: "*")]
public IEnumerable<Product> GetAllProducts()
{
    return products;
}
}
请求标题

Accept  application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Authorization   Basic 1234567890
Content-Type    application/json; charset=utf-8
Host    webapi.server.com
Origin  local-pc
Referer local-pc/Index.aspx
User-Agent  Mozilla/5.0 (Windows NT 6.2; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0
Access-Control-Allow-Orig...    *
Cache-Control   no-cache
Content-Length  61
Content-Type    application/json; charset=utf-8
Date    Thu, 07 Nov 2013 11:48:11 GMT
Expires -1
Pragma  no-cache
Server  Microsoft-IIS/8.0
X-AspNet-Version    4.0.30319
X-Powered-By    ASP.NET
响应标题

Accept  application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Authorization   Basic 1234567890
Content-Type    application/json; charset=utf-8
Host    webapi.server.com
Origin  local-pc
Referer local-pc/Index.aspx
User-Agent  Mozilla/5.0 (Windows NT 6.2; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0
Access-Control-Allow-Orig...    *
Cache-Control   no-cache
Content-Length  61
Content-Type    application/json; charset=utf-8
Date    Thu, 07 Nov 2013 11:48:11 GMT
Expires -1
Pragma  no-cache
Server  Microsoft-IIS/8.0
X-AspNet-Version    4.0.30319
X-Powered-By    ASP.NET

不再在Thread.CurrentPrinicipal上设置主体。在HttpRequestContext上使用主体。

在我的例子中,遵循Darrels方法,我注释了下面的内容并使用了他的方法。它工作得很好!。。。节省我几个小时

// Thread.CurrentPrincipal = PrincipalProvider
//     .CreatePrincipal(parsedCredentials.Username, parsedCredentials.Password);


   request.GetRequestContext().Principal = PrincipalProvider
       .CreatePrincipal(parsedCredentials.Username, parsedCredentials.Password);

将以下内容添加到rest/resource服务器和身份验证服务器web.config


您必须使用

生成自己的密钥,非常感谢Darrel。你成就了我的一天:)(竖起大拇指)。通过将此更改为,修复了此问题。request.GetRequestContext().Principal=新的GenericPrincipal(标识,新字符串[0]);谢谢,你救了我一天:)先生,你赢了互联网。为了解决这个问题,我奋斗了一周。真的非常感谢,really@Darrel请更新您的答案以包含解决问题的代码