[英]oAuth2 token request failing using C# HttpClient but working in Postman
I am trying to request an oAuth token in C# doing exactly what Postman (where it works) is doing, but I keep getting Unauthorized.我正在尝试在 C# 中请求一个 oAuth 令牌,而这正是 Postman(它工作的地方)正在做的事情,但我一直在未经授权。 I can't figure out what Postman is doing differently.
我不知道 Postman 有什么不同。
Here is my code below:下面是我的代码:
var request = new HttpRequestMessage(HttpMethod.Post, "https://myapi/OAuth/Token/")
{
Content = new FormUrlEncodedContent(new KeyValuePair<string?, string?>[]
{
// new("client_id", _clientId),
// new("client_secret", _clientSecret),
// new("scope", "company-api"),
new ("Content-Type", "application/x-www-form-urlencoded"),
new("grant_type", "client_credentials")
})
};
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", System.Convert.ToBase64String(Encoding.ASCII.GetBytes($"{_clientId}:{_clientSecret}")));
using var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
response.EnsureSuccessStatusCode();
await using var responseContentStream = await response.Content.ReadAsStreamAsync();
var accessToken = await JsonSerializer.DeserializeAsync<AccessToken>(
responseContentStream, JsonSerializerOptions.Default);
Here is what my settings look like in postman:这是我在 postman 中的设置:
First of all, your issue is that you're using the wrong Encoding when generating your Basic auth header content.首先,您的问题是您在生成 Basic auth header 内容时使用了错误的编码。
Switch from ASCII to UTF8:从 ASCII 切换到 UTF8:
_httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Basic",
System.Convert.ToBase64String(Encoding.UTF8.GetBytes($"{_clientId}:{_clientSecret}")));
Once you solve this issue, you might want to look into making your life easier to actually read the AccessToken from the response.解决此问题后,您可能想考虑让您的生活更轻松,以便从响应中实际读取 AccessToken。 I would recommend using the
ReadFromJsonAsync<T>
extension method for HttpContent:我建议对 HttpContent 使用
ReadFromJsonAsync<T>
扩展方法:
var jsonData = await response.Content.ReadFromJsonAsync<AccessToken>();
You'll need the System.Net.Http.Json
using statement to get access to the method.您需要使用
System.Net.Http.Json
using 语句来访问该方法。
If you still have issues deserializing the Json, the ReadFromJsonAsync<T>
method takes JsonSerializerOptions
as an optional parameter to help you adjust to your incoming data.如果您在反序列化 Json 时仍然遇到问题,
ReadFromJsonAsync<T>
方法将JsonSerializerOptions
作为可选参数来帮助您调整传入数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.