对Google API的GET调用以“未经授权"响应
更新:解决了这个问题.我DID需要添加授权标头,如下面回答的那样,但是我也相信我的特定用例的问题是访问令牌(我通过Postman验证了)需要更多的范围来完全对我进行身份验证,这是有道理的,因为此API包含调查我尝试访问的链接(也已链接到Google帐户).一旦我将访问调查所需的额外范围以及下面的授权标头代码添加到令牌请求中,便能够成功连接.
有关在C#代码中添加范围的更多信息,请参见: http://www .oauthforaspnet.com/providers/google/
More info on adding scopes to C# code can be found here: http://www.oauthforaspnet.com/providers/google/
希望这可以帮助遇到类似问题的任何人.谢谢大家!
我正在尝试对Google API进行GET调用,但是在我登录Gmail时,它始终显示未经授权"响应.我已经在StartUp.Auth.cs中实现了Google+登录,甚至保存了访问令牌供以后使用.
I am trying to make a GET call to a Google API but it keeps responding with "Unauthorized" while I am logged in to Gmail. I've already implemented Google+ Sign-In in StartUp.Auth.cs and even saved the access token for later use.
那么我如何获得HttpClient的授权?
So how do I get the HttpClient to authorize me?
我有一个可用的访问令牌,但是我不知道如何正确传递它.我已经看到了带有用户名和密码的示例,但是如果我已经具有访问令牌,就不需要传递那些参数了吗?如果有的话,在运行解决方案之前注销时,如果需要,我应该能够将用户重定向到登录页面.
I have an access token available but I do not know how to pass it in properly. I've seen examples with usernames and passwords, but I should not need to pass those parameters if I already have an access token? If anything, I should be able to have the user redirected to a login page instead if needed when I log out before running the solution.
在运行项目时,我期望的是GET调用以json形式返回的结果,但是它始终表示我是未经授权",并且我可能在某处缺少1行代码.
What I am expecting when the project is run, is the result of the GET call to come back in the form of json but it always says I'm "Unauthorized" and I am probably missing 1 line of code somewhere...
这是我正在使用的代码:
Here is the code I am using:
using (HttpClient client = new HttpClient())
{
string _url = "https://www.googleapis.com/consumersurveys/v2/surveys?key={MY_API_KEY}";
client.BaseAddress = new Uri(_url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
using (HttpResponseMessage response = client.GetAsync(_url).Result)
{
if (response.IsSuccessStatusCode)
{
using (HttpContent content = response.Content)
{
var Content = content.ReadAsStringAsync();
ViewBag.GoogleResponse = Content.ToString();
}
}
else
{
// THIS IS ALWAYS UNAUTHORIZED!
ViewBag.GoogleResponse = response.StatusCode + " - " + response.ReasonPhrase;
}
}
}
请提供想法或建议.谢谢!
Please help with ideas or suggestions. Thanks!
您需要在Authorization
标头中传递身份验证令牌:
You need to pass the auth token in an Authorization
Header:
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);