【问题标题】:why An error is created when creating the token为什么创建令牌时会创建错误
【发布时间】:2020-05-22 04:25:21
【问题描述】:
 public static void CreateToken()
    {

        HttpClient client = new HttpClient();
        client.DefaultRequestHeaders.Add("grant_type", "client_credentials");
        var UserPassJson = "{\"username\": \"mucode\",\"password\": \"mypassword\"}";

        HttpContent content = new StringContent(UserPassJson, Encoding.UTF8, "application/json");

        var response = client.PostAsync(new Uri("https://api.sandbox.paypal.com/v1/oauth2/token"), content).Result;
        if (response.IsSuccessStatusCode)
        {
            var responseContent = response.Content;
            string responseString = responseContent.ReadAsStringAsync().Result;
            Console.WriteLine(responseString);
        }
    }

为什么 response.IsSuccessStatusCode 显示状态码 401?什么原因导致故障? 什么操作会导致成功?

【问题讨论】:

标签: c# asp.net api httpclient access-token


【解决方案1】:

documentation 指定您应该使用basic authentication 传递用户名和密码,并且您应该传递一个包含grant_type=client_credentials 的表单编码正文。

目前,您的代码将 grant_type 添加为标题,并将用户名和密码作为 JSON 对象发布在正文中。

更正您的代码以按照文档所述的方式进行操作,我们得到:

HttpClient client = new HttpClient();
byte[] authBytes = System.Text.Encoding.ASCII.GetBytes("mucode:mypassword");
string base64Auth = Convert.ToBase64String(authBytes);
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", base64Auth);

HttpContent content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("grant_type", "client_credentials") });

var response = client.PostAsync(new Uri("https://api.sandbox.paypal.com/v1/oauth2/token"), content).Result;
if (response.IsSuccessStatusCode)
{
    var responseContent = response.Content;
    string responseString = responseContent.ReadAsStringAsync().Result;
    Console.WriteLine(responseString);
}

附:我建议阅读You're using HttpClient wrong and it is destabilizing your software 和后续You're (probably still) using HttpClient wrong and it is destabilizing your software。我还建议使用此方法async 并将链一直向上设置async

【讨论】:

  • 非常感谢它有效!问题:access_token只要不被使用就不会改变吗?
  • 我不确定使用 PayPal 可以使用多长时间(我没有使用过他们的 API)。您应该在响应中检查 expires_in 以查看它何时过期。通常,许多 OAuth API 允许您请求“offline_access”范围,该范围还将在您的访问令牌过期时提供刷新令牌(您使用刷新令牌来请求新的访问令牌),尽管我不确定是否它与 PayPal 的工作方式类似。在文档页面上搜索“刷新”似乎没有显示任何内容,因此在 PayPal 上可能无法实现,如果您收到 401,您只需要重新验证?
猜你喜欢
  • 1970-01-01
  • 2011-01-19
  • 1970-01-01
  • 2016-08-13
  • 1970-01-01
  • 2020-08-04
  • 1970-01-01
  • 2014-12-16
  • 2016-08-18
相关资源
最近更新 更多