【问题标题】:Asana API 403 Response in C#C# 中的 Asana API 403 响应
【发布时间】:2020-06-02 08:57:10
【问题描述】:

我正在尝试实现一个可与 Asana API 配合使用的 Xamarin 应用。

我已经成功实现了 Asana 文档here 中记录的 OAuth... 至少我认为它是成功的。我从 HTTP 状态“OK”的 HTTPResponse 中的令牌端点获取访问令牌。

但是当我转身尝试使用相同的访问令牌进行 API 调用时,我收到 403 Forbidden 错误。我在我的浏览器中尝试了相同的 API 调用(登录到 Asana 后),它运行良好,这让我相信我确实可以访问该资源,我必须在授权请求时遇到问题。

有问题的 API 调用是 (documented here):https://app.asana.com/api/1.0/workspaces

我的C#代码如下(简称相关部分,并假设ACCESS_TOKEN包含我从令牌交换端点获得的访问令牌):

HttpClient client = new HttpClient();
client.BaseAddress = "https://app.asana.com/api/1.0";
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", ACCESS_TOKEN);
client.DefaultRequestHeaders.Add("Accept", "application/json");

然后我在以下函数中使用这个HttpClient(命名为client):

// Returns a list of the Asana workspace names for the logged in user.
private async Task<List<string>> GetWorkspacesAsync()
{
    List<string> namesList = new List<string>();

    // Send the HTTP Request and get a response.
    this.UpdateToken(); // Refreshes the token if needed using the refresh token.
    using (HttpResponseMessage response = await client.GetAsync("/workspaces"))
    {
        // Handle a bad (not ok) response.
        if (response.StatusCode != HttpStatusCode.OK)
        {
            //  !!!THIS KEEPS TRIGGERING WITH response.StatusCode AS 403 Forbidden!!!

            // Set up a stream reader to read the response.
            // This is for TESTING ONLY
            using (StreamReader reader = new StreamReader(await response.Content.ReadAsStreamAsync()))
            {
                // Extract the json object from the response.
                string content = reader.ReadToEnd();
                Debug.WriteLine(content);
            }

            throw new HttpRequestException("Bad HTTP Response was returned.");
        }

        // If execution reaches this point, the Http Response returned with code OK.

        // Set up a stream reader to read the response.
        using (StreamReader reader = new StreamReader(await response.Content.ReadAsStreamAsync()))
        {
            // Extract the json object from the response.
            string content = reader.ReadToEnd();
            JsonValue responseJson = JsonValue.Parse(content);

            foreach (JsonValue workspaceJson in responseJson["data"])
            {
                string workspaceName = workspaceJson["name"];
                Debug.WriteLine("Workspace Name: " + workspaceName);

                namesList.Add(workspaceName);
            }
        }
    }

    // I have other awaited interactions with app storage in here, hence the need for the function to be async.

    return namesList;
}

【问题讨论】:

    标签: c# xamarin oauth httprequest asana-api


    【解决方案1】:

    终于找到答案了。看起来我错误地使用了HttpClient;一个微妙的东西应该是等​​效的,但不是由于它的实现方式。

    答案

    我需要将最后的斜杠放在HttpClientBaseAddress 属性的末尾,而不是特定请求的相对地址的开头。 This answered question explains this.

    修复我的代码

    我需要更改BaseAddress 的设置:

    HttpClient client = new HttpClient();
    client.BaseAddress = "https://app.asana.com/api/1.0/"; // FINAL SLASH NEEDED HERE
    

    并从请求的相对地址中删除斜线:​​

    // DO NOT put slash before relative address "workspaces" here
    using (HttpResponseMessage response = await client.GetAsync("workspaces"))
    

    为什么我得到原来的错误

    HttpClientBaseAddress 与我在GetAsync() 中指定的相对URI 组合在一起时,它丢弃了一些基地址,因为最后的斜杠不包括在内。将 BaseAddress 与相对 URI 组合得到的地址是有效的 URL,但在 Asana 中不是有效的页面/API 调用。因此,Asana 自动重定向到登录页面,当然,从那里禁止其余的 API 调用。

    我是如何发现这一点的

    在调试过程中,我获取了在我的应用通过 Asana 授权期间返回的访问令牌。然后,我自己在Postman 中重新创建了对“/workspaces”API 的请求,并且请求按预期工作。这证实了我的授权工作正常,问题必须与特定请求而不是授权有关。在调试过程中,我查看了HttpResponseMessage,它有一个名为RequestMessage 的属性,其中包括GetAsync() 发出请求的实际URL。我观察到来自 Asana 的登录 URL,而不是我指定的 BaseAddress... 这导致了我的问题/ 上面链接的答案。

    希望这个解释对遇到类似错误的人有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多