Leo*_*ens 1 authentication google-api oauth-2.0 windows-8 windows-runtime
我正在尝试使用Google OAuth2 API为我的Windows 8应用程序交换我的授权代码,但我不断收到HTTP 400错误.
这是我执行请求的方式(简化):
var url = "https://accounts.google.com/o/oauth2/token";
var body = "code=4/LEXF1iAVRZvfCfdQg9r1aFqoYDgV&client_id=904019870963.apps.googleusercontent.com&client_secret=[removed]&redirect_uri=urn:ietf:wg:oauth:2.0:oob&grant_type=authorization_code";
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.PostAsync(new Uri(url), new StringContent(body));
response.EnsureSuccessStatusCode();
Run Code Online (Sandbox Code Playgroud)
Visual Studio通常只是给我一个HTTP 400错误的请求错误,当我在Fiddler中尝试同样的事情时我也得到了一个HTTP 400错误,但是这个内容如下:
21
{
"error" : "invalid_request"
}
0
Run Code Online (Sandbox Code Playgroud)
我阅读了有关Google OAuth的所有文档,我在Google和StackOverflow上搜索了此问题,我尝试在我的代码中更改所有不同类型的内容(UrlEncode等),我使用了Google API Playground来查看它的请求类型执行并将其与我自己的请求进行比较(除了返回URL,身份验证代码和用户代理之外,找不到区别).无论我做什么,我都无法做到这一点,我已经被困了几个小时了.
有人可以帮我从这里出去吗?
阅读正文内容以获取您在Fiddler中发现的错误json.
HttpClient httpClient = new HttpClient();
var response = httpClient.PostAsync(new Uri(url), new StringContent(body)).Result;
var content = response.Content.ReadAsStringAsync().Result;
Run Code Online (Sandbox Code Playgroud)
内容现在成立:
{
"error" : "invalid_request"
}
Run Code Online (Sandbox Code Playgroud)
您可以通过指定错误类型来在对象中投影错误,如:response.Content.ReadAsAsync().
对于无效的请求部分,您应该使用UrlEncode.我知道你说你试过了,但在正确的位置应用它确实解决了你的问题.
var body = "code="+WebUtility.UrlEncode("4/LEXF1iAVRZvfCfdQg9r1aFqoYDgV")+
"&redirect_uri="+WebUtility.UrlEncode("https://yoursite...")+
"&client_id=904019870963.apps.googleusercontent.com" +
"&scope=" +
"&client_secret=********" +
"&grant_type=authorization_code";
HttpClient httpClient = new HttpClient();
var response = httpClient.PostAsync(new Uri(endpoint),
new StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded")).Result;
Run Code Online (Sandbox Code Playgroud)
这是适合我的代码.应该也适合你.
| 归档时间: |
|
| 查看次数: |
528 次 |
| 最近记录: |