【问题标题】:restsharp and Postmanrestsharp 和邮递员
【发布时间】:2019-07-04 16:44:57
【问题描述】:

我正在尝试使用 RestSharp 代码从 ZOHO 获取 OAuth2 访问令牌。 Postman 模拟工作正常,所以我知道我的代码中缺少一些东西。

我总是得到“无效的客户 ID”结果状态。但是在 Postman 中,当我单击“获取新的访问令牌”时,它可以工作并返回一个代码。我有与 Postman 授权选项卡中相同的项目(client_id、client_secret 等)。在 Postman 中,“Body”设置为“none”,并且没有参数或标题。我的代码和邮递员之间的唯一区别是邮递员需要回调 URL。我的代码正在尝试使用绕过回调 URL 的“自我客户端”获取代码。

我尝试了几种不同的请求调用替代方案,包括 ParameterType.Body 和 ParameterType.GetOrPost。 GetOrPost 和表单一样吗?

client = New RestClient(ZOHO_API_URL)
request = New RestRequest(TokenUrl, Method.POST)
request.AddHeader("content-type", "application/x-www-form-urlencoded") ' also tried: "application/json")
request.AddParameter("grant_type", "authorization_code", 
    ParameterType.GetOrPost)
request.AddParameter("client_id", Client_ID, ParameterType.GetOrPost)
request.AddParameter("client_secret", Client_Secret, 
    ParameterType.GetOrPost)
request.AddParameter("code", Grant_Token, ParameterType.GetOrPost)
response = client.Execute(request)

这是翻译后的 RestSharp 的 Postman 代码:

var client = new RestClient("http://");
var request = new RestRequest(Method.POST);
request.AddHeader("Postman-Token", "xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxx");
request.AddHeader("cache-control", "no-cache");
IRestResponse response = client.Execute(request);

关于我做错了什么的任何想法。我试图查看 Fiddler 遇到的原始数据,但是当我这样做时,Postman 表示失败。 我需要使用什么代码来复制 Postman 正在做的事情?

如果还需要回调 URL,我该如何实现?

【问题讨论】:

  • 您可能需要为 Restsharp 客户端激活 cookie,Client.CookieContainer = new System.Net.CookieContainer();

标签: oauth-2.0 restsharp


【解决方案1】:

我快速查看了 ZoHo REST API 文档,看来您应该使用受限输入设备authentication flow

从他们的帮助页面我可以理解,你确实需要做一个POST请求,但参数必须指定为查询参数:

https://accounts.zoho.com/oauth/v3/device/code?
client_id=1000.GMB0YULZHJK411248S8I5GZ4CHUEX0&
scope=AaaServer.profile.READ&
grant_type=device_request

您还可以使用client.UseJson() 将 JSON 设置为序列化和内容类型的默认值。

【讨论】:

    【解决方案2】:

    可能 Postman 正在跟踪来自您的 API 端点的重定向,因为 Postman 与 RestSharp 的功能不同(可能缺少尾部斜杠或类似内容)。

    尝试添加

    client.FollowRedirects = false;
    

    到您的 RestSharp 代码并分析结果。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    • 2017-12-30
    • 2018-02-04
    • 2019-02-17
    • 1970-01-01
    • 2020-01-21
    • 2018-03-09
    相关资源
    最近更新 更多