简体   繁体   English

C# HttpClient cannot send authorization header to ASP.NET Core Web API

[英]C# HttpClient cannot send authorization header to ASP.NET Core Web API

I am trying to use C# HttpClient from ASP.NET MVC to make a request to an API.我正在尝试使用 ASP.NET MVC 中的 C# HttpClient 向 API 发出请求。 My API is running on .NET 6.0.我的 API 在 .NET 6.0 上运行。

httpClient.BaseAddress = new Uri(_url);
httpClient.DefaultRequestHeaders.Clear();
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue($"Bearer", $"{token}");
var serialized = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json");
var httpResponseMessage = await httpClient.PutAsync(urlToSend, serialized);

Here is my code.这是我的代码。 I tried all the possibilities I saw on google.我尝试了我在谷歌上看到的所有可能性。 But when sending request, I can't send Authorization header.但是在发送请求时,我无法发送授权 header。

I can send it with Postman.我可以用 Postman 发送。

Here is my API code:这是我的 API 代码:

    [Consumes("application/json")]
    [Produces("application/json", "text/plain")]
    [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(IResult))]
    [ProducesResponseType(StatusCodes.Status400BadRequest, Type = typeof(IResult))]
    [HttpPut("changeuserpassword")]
    public async Task<IActionResult> ChangeUserPassword([FromBody] ChangePasswordCommand changePasswordCommand)
    {
        var accessToken = Request.Headers[HeaderNames.Authorization];
        return GetResponseOnlyResult(await Mediator.Send(changePasswordCommand));
    }

Note: In my _url, I use http, not https.注意:在我的 _url 中,我使用 http,而不是 https。

I'm not sure but maybe the [AllowAnonymous] attribute remove the Authorization header from request just because it does not make sense if no authorization is needed.我不确定,但也许[AllowAnonymous]属性从请求中删除了 Authorization header 只是因为如果不需要授权就没有意义。 Have you checked if the sent request contains the header using a tool like fiddler?您是否使用 fiddler 之类的工具检查了发送的请求是否包含 header?

Please review this link.请查看此链接。 Allow Anonymous will ignore the authentication header Allow Anonymous 将忽略身份验证 header

https://github.com/dotnet/aspnetcore/issues/30546 https://github.com/dotnet/aspnetcore/issues/30546

I tried with the code.我尝试了代码。 It seems working fine for me.对我来说似乎工作正常。 Here is my code of console app这是我的控制台应用程序代码

try
            {

                ChangePasswordCommand passobj = new ChangePasswordCommand() { password = "new password"};

                string _url = "https://localhost:44395/api/Values/";

                var httpClient = new HttpClient();
                httpClient.BaseAddress = new Uri(_url);
                httpClient.DefaultRequestHeaders.Clear();
                httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue($"Bearer", $"MYTOKEN");
                var serialized = new StringContent(JsonConvert.SerializeObject(passobj), Encoding.UTF8, "application/json");
                var httpResponseMessage = await httpClient.PutAsync("changeuserpassword", serialized);
            }
            catch (Exception ex) { 
            
            }

And here is controler Api这是控制器 Api

[AllowAnonymous] [允许匿名]

    [Consumes("application/json")]
    [Produces("application/json", "text/plain")]
    
    [HttpPut("changeuserpassword")]
    public async Task<IActionResult> ChangeUserPassword(ChangePasswordCommand changePasswordCommand)
    {
        var accessToken = Request.Headers[HeaderNames.Authorization];

        return Ok();
    }

I solved the problem by changing my base url from HTTP to HTTPS.我通过将我的基础 url 从 HTTP 更改为 HTTPS 解决了这个问题。

I tried with Fiddler and I got the same problem when I request to HTTP.我尝试使用 Fiddler,当我向 HTTP 请求时遇到了同样的问题。

So thanks to @olivier-duhart.感谢@olivier-duhart。

To add to the accepted answer, the problem gets solved by changing from HTTP to HTTPS is due to the fact that, the Authorization header gets stripped during redirects.为了增加已接受的答案,通过从 HTTP 更改为 HTTPS 来解决问题是因为授权 header 在重定向期间被剥夺。 This behavior is for security concerns and is by design, as mentioned in the github discussion here .此行为是出于安全考虑,并且是设计使然,如github讨论中所述。

The same behavior may not be seen when using Postman vs HttpClient for example, is due to the way that different clients, have differing mechanisms, by which the subsequent requests (following a response status 30X) to the redirect location are handled.例如,在使用 Postman 与 HttpClient 时可能不会看到相同的行为,这是由于不同的客户端具有不同的机制,通过这些机制处理对重定向位置的后续请求(响应状态为 30X 之后)。

Also a great answer elsewhere on stackoverflow: Authorization header is lost on redirect在stackoverflow的其他地方也是一个很好的答案: Authorization header is lost on redirect

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 C# HttpClient,如何将字符串 HttpContent POST 到 ASP.net Core Web API? - Using C# HttpClient, how to POST a string HttpContent to ASP.net Core web API? ASP.NET Core Web API如何从客户端C#发送json对象 - asp.net core web api how to send json object from client side c# 无法使用 C# 客户端将 IFormFile 发送到 ASP.Net Core Web API - unable to send IFormFile to ASP.Net Core Web API using C# client 使用 C# ASP.NET Core Web API 进行谷歌身份验证 - Google authentication with C# ASP.NET Core Web API C# ASP.NET Core Web API 包含与 where - C# ASP.NET Core Web API include with where HttpClient POST Protobuf ByteArray 到 ASP.NET 核心 Web API - HttpClient POST Protobuf ByteArray to ASP.NET Core Web API 处理身份验证/授权:ASP.NET Core Web 应用程序 =&gt; ASP.NET Core Web API =&gt; SQL - Handling authentication/authorization: ASP.NET Core Web Application => ASP.NET Core Web API => SQL 在DelegatingHandler ASP.NET Web API中添加BearerToken授权标头 - Addition of BearerToken Authorization Header in DelegatingHandler ASP.NET Web API ASP.NET Core Web API 和角色授权 - ASP.NET Core Web API and roles authorization 勾选IP和JWT 在ASP.NET核中授权Web Api - Check IP with JWT Authorization in ASP.NET Core Web Api
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM