gpt4 book ai didi

c# - ASP.NET WebAPI 基本身份验证总是失败,因为 401/未授权

转载 作者:太空狗 更新时间:2023-10-29 17:36:48 27 4
gpt4 key购买 nike

尝试使用基本身份验证保护我的 ASP.NET Web API-2,但它总是以错误结束:

401/Unauthorized
Authorization has been denied for this request.

下面是我的 Controller 和 ajax 请求代码片段以及请求和响应 header 。

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

return base.SendAsync(request, cancellationToken);

问:那为什么最后会显示 401/unauthorized 呢?

如果我从 Controller 操作中删除 [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);
}

我的 Controller

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;
}
}

我的 AJAX 请求

$.ajax({
type: "GET",
url: "http://webapi.server.com/test/products",
crossDomain: true,
dataType: "json",
contentType: "application/json; charset=utf-8",
headers: { Authorization: "Basic 1234567890" },
success: function (data) {
alert(data);
},
error: function (err) {
alert(err);
}
});

请求 header

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

响应 header

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 上设置 Principal。在 HttpRequestContext 上使用主体。

关于c# - ASP.NET WebAPI 基本身份验证总是失败,因为 401/未授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19835665/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com