HttpResponeMessage 返回 401(未经授权)

Posted

技术标签:

【中文标题】HttpResponeMessage 返回 401(未经授权)【英文标题】:HttpResponeMessage returns 401 (Unauthorized) 【发布时间】:2021-05-04 12:38:35 【问题描述】:

我正在尝试连接到一个 api,但我得到以下结果:

StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:

  Vary: Origin
  Access-Control-Allow-Credentials: true
  Access-Control-Allow-Origin: https://example.url
  Date: Sat, 30 Jan 2021 22:56:45 GMT
  Set-Cookie: TS0182ab0d=0180bb6f22515cbe2cddec42f2bdc8cb4b394bf2447928c095c41f950fab6ce3b59180574be0cf84ba91749969bb6cfafcaf801f7d; Path=/; Domain=.api2.mofidonline.com
  Content-Length: 0

这是我的标题

request.Headers.TryAddWithoutValidation("authority", "api2.example.url");
request.Headers.TryAddWithoutValidation("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (Khtml, like Gecko) Chrome/88.0.4324.104 Safari/537.36");
request.Headers.TryAddWithoutValidation("x-requested-with", "XMLHttpRequest");
string str = "BasicAuthentication" + mCookie["api-token"];
request.Headers.TryAddWithoutValidation("authorization", str);
request.Headers.TryAddWithoutValidation("accept", "*/*");
request.Headers.TryAddWithoutValidation("origin", "https://example.url");
request.Headers.TryAddWithoutValidation("sec-fetch-site", "same-site");
request.Headers.TryAddWithoutValidation("sec-fetch-mode", "cors");
request.Headers.TryAddWithoutValidation("sec-fetch-dest", "empty");
request.Headers.TryAddWithoutValidation("referer", "https://example.url/Home/Default/page-1");
request.Headers.TryAddWithoutValidation("accept-language", "en-US,en;q=0.9");

【问题讨论】:

它是 Basic 而不是 BasicAuthentication 不是吗? 【参考方案1】:

这是不正确的:

string str = "BasicAuthentication" + mCookie["api-token"];

它是“基本”,然后您需要一个空格,后跟用户名和密码,并用冒号连接,作为凭据的 Base64 编码字符串。

例如:

string base64EncodedCredentials = Convert.ToBase64String(Encoding.ASCII.GetBytes("username:password"));
string authorizationHeader = "Basic " + base64EncodedCredentials;

【讨论】:

以上是关于HttpResponeMessage 返回 401(未经授权)的主要内容,如果未能解决你的问题,请参考以下文章

MVC5 抛出 401 的 HttpException 返回 500

授权总是返回 401

等待质量门返回 401

Spring安全许可全部返回401

Django Tastypie 总是返回 401 未经授权

Spring Security 测试返回 401(未经授权)