【发布时间】: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