【问题标题】:Google Api get access_token request returns invalid_requestGoogle Api 获取 access_token 请求返回 invalid_request
【发布时间】:2012-04-03 07:27:01
【问题描述】:

我正在尝试使用 javascript 获取 Google APi 的 access_token,但总是收到错误消息:invalid_request。有我的代码:

var options = {
    url: tokenURL,
    type: "POST",
    headers: { "Content-type": "application/x-www-form-urlencoded"},
    dataType: "json",
    data: {
        "code":successCode,
        "client_id": clietId,
        "client_secret": clientSecret,
        "grant_type": "authorization_code",
        "redirect_url": "urn:ietf:wg:oauth:2.0:oob"
    },
    complete: function (e) {
        alert(e.status);
    },
};

$.ajax(options);

我还尝试使用简单的 html 表单发出 POST 请求,它可以工作。

<form method="post" action="https://accounts.google.com/o/oauth2/token">
<input name="code" type="text" value="##code##" />
<input name="client_id" type="text" value="##client_id##" />
<input name="client_secret" type="text" value="##client_secret##" />
<input name="grant_type" type="text" value="authorization_code" />
<input name="redirect_uri" type="text" value="urn:ietf:wg:oauth:2.0:oob" />

<input type="submit" /></form>

我不知道 javascript 请求有什么问题。我是否缺少一些参数或标题?

【问题讨论】:

  • 尝试使用 Firebug 并查看 Net 选项卡以查看您从表单发出的请求与 ajax 请求之间的区别
  • 我尝试使用 Fiddler,除了 cookie 没有发现任何区别
  • @pauliusnrk 你有什么解决办法吗?

标签: javascript jquery xmlhttprequest google-api oauth-2.0


【解决方案1】:

看起来data(在第一个示例中)的编码与内容类型不匹配。

data 的编码似乎是 application/json,但指定的 content-type 是 application/x-www-form-urlencoded。

您需要将data的编码更改为urlencoded。

   data: "code=successCode&client_id=clientId&client_secret=clientSecret&grant_type=authorization_code&redirect_url=urn:ietf:wg:oauth:2.0:oob"

【讨论】:

  • 按照你说的设置数据,连请求都不发送:var options = { url: 'https://accounts.google.com/o/oauth2/token', type: "POST", headers: { "Content-type": "application/x-www-form-urlencoded"}, dataType: "json", data: "code=code&amp;client_id=clientId&amp;client_secret=clientSecret&amp;redirect_uri=myuri&amp;grant_type=authorization_code", complete: function (e) { alert(e); alert(e.status); }, }; $.ajax(options);
猜你喜欢
  • 2012-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-08
  • 2012-01-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多