使用GM_xmlhttpRequest交换访问令牌的Quire授权代码

时间:2019-10-13 09:14:58

标签: javascript userscripts quire-api

这可能是一个愚蠢的问题,我尝试按照quire-api-blog给出的说明进行操作,但仍然无法从Tampermonkey javascript用户脚本获取令牌。

GM_xmlhttpRequest的FYI语法在https://www.tampermonkey.net/documentation.php?ext=dhdg#GM_xmlhttpRequest上可用

我正在使用以下代码:

GM_xmlhttpRequest({
    method: "POST",
    url: "https://quire.io/oauth/token",
    data: JSON.stringify({
              grant_type: "authorization_code",
              code: "xxx",
              client_id: ":yyy",
              client_secret: "zzz"
          }),
    onload: function(r){
        console.log(r);
    }
});

这将在控制台中返回以下对象:

finalUrl: "https://quire.io/oauth/token"
​
readyState: 4
​
response: 
​
responseHeaders: "content-encoding: gzip\r\ncontent-type: text/plain; charset=utf-8\r\ndate: Sun, 13 Oct 2019 09:04:26 GMT\r\nserver: nginx/1.17.3\r\nset-cookie: DARTSESSID=7d20dcf1f0eae6ce0f69d9fe615e9ce5; Path=/; HttpOnly\r\nx-content-type-options: nosniff\r\nx-firefox-spdy: h2\r\nx-frame-options: SAMEORIGIN\r\nx-xss-protection: 1; mode=block\r\n"
​
responseText: 
​
responseXML: 
​
status: 400
​
statusText: "Bad Request"

知道发生了什么事吗?

提前谢谢您的好意。

拉斐尔

2 个答案:

答案 0 :(得分:1)

您需要特别注意请求的content-type。不同的XHR API使用不同的默认值。

OAUTH2 Specification for the Access Token Request将内容类型描述为application/x-www-form-urlencoded

默认情况下,GreaseMonkey使用JSON发送请求,可以通过设置Content-Type标头并使用'x-www-form-urlcoded'将数据编码为String来更改请求

GM.xmlHttpRequest({
  method: "POST",
  url: "https://quire.io/oauth/token",
  data: "grant_type=authorization_code&code=xxx&client_id=yyy&client_secret=zzz",
  headers: {
    "Content-Type": "application/x-www-form-urlencoded"
  },

jquery.ajax()会自动将默认的Content-Type设置为application / x-www-form-urlencoded

重要说明: $ .ajax()的用法表示浏览器中的用法。如果是这样,那就不要做!将client_secret暴露给浏览器中运行的应用程序将使任何人都可以身份验证为您的身份并使用grant_type: client_authentication访问您的项目。到目前为止,Quire API要求您运行专用服务器,从该服务器必须执行访问令牌请求,以避免暴露client_secret。如果您在服务器端使用jquery,那就可以了。

有一个开放的Issue#8,它也支持不使用client_secret(适用于SPA或浏览器扩展程序)的客户端授权代码流。

答案 1 :(得分:0)

与此同时,对于它的价值,我已经能够使其与jQuery $ .ajax()命令一起使用,请参见https://api.jquery.com/jquery.ajax/,它给出了:

$.ajax({
    type: "POST",
    url: "https://quire.io/oauth/token",
    data: {
        grant_type: "authorization_code",
        code: "xxx",
        client_id: ":yyy",
        client_secret: "zzz"
    },
    success: function(r){
        console.log(r);
    }
});

仍然很想从理智的角度知道GM_xmlhttpRequest出了什么问题

相关问题