c# - HttpClient未在.Net Core 3.1中发送授权承载 token

标签 c# asp.net asp.net-web-api

我有一个使用 HttpClient 调用 ASP.NET Core WebApi 的 ASP.NET Core MVC 应用程序,但我必须发送授权 header ,问题是我的 HttpClient 不会发送授权 header 。
我有一个用于调用具有以下构造函数的 webapi 的服务:

        public ApiService(HttpClient httpClient, IHttpContextAccessor accessor)
        {
            string token = accessor.HttpContext.User.FindFirstValue("JWToken"); // gets user token
            httpClient.BaseAddress = new Uri(AppSettings.BaseUrlApi); //sets the base URL of the webapi
            httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
            httpClient.Timeout = TimeSpan.FromMinutes(1);
            httpClient.DefaultRequestHeaders.Authorization
                         = new AuthenticationHeaderValue("Bearer", token);

            _httpClient = httpClient; // assigns to a private property "private readonly HttpClient _httpClient;"
        }
然后,当我将数据发布到 webapi 时,我使用以下方法:
        public async Task<User> PostAsync(string url, User user)
        {
            StringContent jsonContent = new StringContent(
                JsonConvert.SerializeObject(user, Formatting.Indented, _jsonSettings), // _jsonSettings is a JsonSerializerSettings object
                Encoding.UTF8,
                "application/json");

            using HttpResponseMessage httpResponse =
                await _httpClient.PostAsync(url, jsonContent);
            httpResponse.EnsureSuccessStatusCode();
            string responseString = await httpResponse.Content.ReadAsStringAsync();

            return JsonConvert.DeserializeObject<User>(responseString, _jsonSettings);
        }
对于不需要 Authorization header 的请求,它工作得很好,但它不发送 Authorization header ,我尝试使用 HttpRequestMessage 然后 SendAsync 实例化一个新的 HttClient,但它从来没有工作,我也尝试使用 httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}"); 但是它不起作用,也 TryAddWithoutValidation ,但不起作用。
最糟糕的是,当我检查我的 httpClient 对象时,授权 token 在那里:
enter image description here
但是随后我从我的 webapi 收到一条 401 消息,当我检查在 webapi 中收到的请求时,授权 header 为空,并且我的 webapi 在收到来自 ajax 调用或失眠和 postman 等应用程序的请求时工作正常。
我无法弄清楚我错过了什么。
编辑:
在我的 webapi 中,到达的请求是:
enter image description here
我的授权 header 是 {}
现在,例如,当我收到来自 insomnia 的请求时,我有以下 header :
enter image description here

最佳答案

您正在使用的代码看起来应该可以工作,我在最后尝试了类似的东西,它按预期添加了 JWT。 401 是否有可能合法地指代错误的 token ?我会尝试解码它:https://jwt.io/并验证其中的所有声明是否有意义(例如过期)并且签名正确。
更新
添加一些与您尝试执行的代码非常相似的代码对我有用,仅供引用,这是通过 API 调用电话,为简单起见将 JWT 生成和命令生成排除在外

var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("Accept", "application/json");

var json = JsonConvert.SerializeObject(command,
    Formatting.None, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });
httpClient.DefaultRequestHeaders.Authorization = 
    new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", jwt);

var content = new StringContent(json, Encoding.UTF8, "application/json");

var response = httpClient.PostAsync("https://api.nexmo.com/v1/calls", content).Result;
我可以确认这肯定会将 JWT 作为不记名 token 添加到 header 中(否则它将无法正常工作)
希望这会有所帮助。

关于c# - HttpClient未在.Net Core 3.1中发送授权承载 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63925434/

相关文章:

c# - 将 HTTPS 页面上的 URL 重写为 HTTP

c# - ServicePointManager 安全协议(protocol)冲突

asp.net - ASP .NET 5 MVC 6 Identity 3 角色声明组

asp.net-mvc - 使用 Web Api 验证 .NET MVC 应用程序

c# - 流畅的 NHibernate : Index was out of range exception with ReferencesAny mapping

c# - 将 Sql Server uniqueidentifier/updated date 列与 Linq to Sql 结合使用 - 最佳方法

c# - 解析路由时 ASP.NET 中的奇怪行为

asp.net - ASP.Net异常-捕获页面或Global.asax中的句柄(Application_Error)

c# - 从 ASP.NET 网站 Webforms 调用 ASP.Net Web API

c# - ASP.NET WebAPI 中的依赖注入(inject) : IHttpControllerActivator vs. IDependencyResolver