首页 > 解决方案 > 如何诊断尝试在 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为我的麻烦获取代码。

欢迎提出故障排除建议、更好的解决方法以及嘲笑我的愚蠢。

标签: c#.net-corepaypaloauth-2.0

解决方案


更新:

我阅读了文档,有几项对我来说很突出:

  • 需要一个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();

推荐阅读