c# - 如何诊断尝试在 c# .NET Core 中获取 OAuth2 不记名令牌的 401 错误?
问题描述
我有一些有限的技能,c++
最近搬进了C# (asp.net)
和azure Web services
。作为一个 PoC,我正在尝试REST
拨打电话PayPal
(我需要在 3 -6 个月内专业地使用它)。
我已经使用此处的说明设置了我的个人PayPal
帐户,并使用 curl 获取了不记名令牌,如链接中所述。惊人的。
我现在正在尝试这样做,.NET Core C#
而我得到的只是一个401 error
. 我已经检查了请求,就标题而言,它似乎与 curl 相同;我认为我要添加的base64
编码凭据与详细 curl 日志中的凭据相同(我base64
通过眼睛检查了两个字符串),因此它必须是我在调用设置中正在做(或不做)的事情. 我正在寻找建议、指点或对我所犯的明显错误大笑。
我已经建立了我认为是命名客户的东西:
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient("PayPal", c =>
{
c.BaseAddress = new Uri("https://api.sandbox.paypal.com/v1/");
c.DefaultRequestHeaders.Add("Accept", "application/json");
c.DefaultRequestHeaders.Add("Accept-Language", "en_US");
});
(为简洁起见,VS 下免费提供的所有其他东西都省略了)。
我因此尝试调用:
string clientCredString = CLIENTID + ":" + SECRET;
var clientCreds = System.Text.Encoding.UTF8.GetBytes(clientCredString);
var client = _clientFactory.CreateClient("PayPal");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", System.Convert.ToBase64String(clientCreds));
var messageBody = new Dictionary<string,string > ();
messageBody.Add("grant_type", "client_credientials");
var request = new HttpRequestMessage(HttpMethod.Get, "oauth2/token")
{
Content = new FormUrlEncodedContent(messageBody)
};
string token;
var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadAsStringAsync();
token = JsonConvert.DeserializeObject<string>(json);
}
else
{
throw new ApplicationException("Well that failed");
}
并401
为我的麻烦获取代码。
欢迎提出故障排除建议、更好的解决方法以及嘲笑我的愚蠢。
解决方案
更新:
我阅读了文档,有几项对我来说很突出:
- 需要一个post动词。
- 用于
FormUrlEncodedContent
客户端凭据。 - 基本身份验证需要用户名和密码(客户端 ID 和密码)
我相信语法应该是:
var client = new HttpClient();
using var request = new HttpRequestMessage(HttpMethod.Post, "...");
request.Content = new Dictionary<string, string>() { "grant_type", "client_credentials" };
request.Headers.Authorization = new AuthenticationHeaderValue("Basic", $"{Encoding.UTF8.GetBytes($"{id}:{secret}")}");
HttpResponseMEssage = response = await client.PostAsync(request);
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
推荐阅读
- python - 如何根据特定条件用列表值替换 Pandas Dataframes 中的元素?
- c++ - 静态链接 libm 以在多台计算机上获得相同的结果
- javascript - 将选择日期限制在今天和前 7 天之间
- java - 如何在 Long 对象的值末尾添加零
- php - PHP 为什么这个简单的数组显示不正确的值
- c# - 虚拟相机 - 从 Opencv 捕获图像帧并传递给 Directshow 过滤器以用于虚拟相机应用程序
- javascript - d3气泡图反应js:如何将气泡保持在图表边界内?
- java - 具有泛型类型的字段可能为 null 的泛型类
- image-processing - 为 CNN 填充尺寸小于 5 x 5 像素的图像
- python - 为什么我的 Frames 选项没有在 tkinter 中显示?