HttpClient未在.Net Core 3.1中发送授权承载令牌

时间:2020-09-16 17:49:06

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

我有一个使用HttpClient调用ASP.NET Core WebApi的ASP.NET Core MVC应用程序,但是我必须发送授权标头,问题是我的HttpClient无法发送授权标头。

我有一个用于调用具有以下构造函数的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标头的请求,它工作得很好,但是它不发送Authorization标头,我尝试使用HttpRequestMessage然后使用SendAsync实例化一个新的HttClient,但是它从未起作用,我也尝试了使用httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");,但它不起作用,TryAddWithoutValidation也不能,但是不起作用。 最糟糕的是,当我检查我的httpClient对象时,授权令牌在那里:

enter image description here

但是随后我从我的webapi收到一条401消息,当我检查在webapi中收到的请求时,授权标头为空,并且当我的webapi收到来自ajax调用或失眠和邮递员之类的应用程序的请求时,它可以正常工作

我不知道自己想念什么。

编辑:

在我的webapi中,到达的请求是: enter image description here

我的授权标头是{}

现在,例如,当我收到失眠的请求时,我有以下标题:

enter image description here

1 个答案:

答案 0 :(得分:2)

您使用的代码看起来应该可以工作,我尝试了类似的操作,并按预期添加了JWT。 401是否可能合法地引用了错误的令牌?我会尝试使用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作为承载令牌添加到标头中(否则将无法正常工作)

希望这会有所帮助。