javascript - GitHub API 的响应未返回具有适当范围的访问 token 来查看私有(private)存储库

标签 javascript rest api

我得到了我想要的响应,但从 GitHub 返回的访问 token 返回时响应中没有范围:

// githubs response

{ 
  access_token: 'a2ed9606c8b06bf00a16dc34584b1509462450a4',
  token_type: 'bearer',
  scope: '' 
}

该 token 无法像我启用了范围的个人访问 token 那样查看私有(private)存储库。我是否做错了什么或没有联系正确的端点?

// backend - Auth.js

var express = require('express');
var router = express.Router();
var fetch = require('isomorphic-fetch');

let token = null;

const createFetchOptions = (method, body = undefined) => {
    const options = {
        method,
        headers: {
            'Content-type': null,
            'Accept': null,
        },
    };

    options.headers['Content-type'] = 'application/json';
    options.headers['Accept'] = 'application/json';
    options.body = JSON.stringify(body);

    return options;
};

const Fetcher = {
    get: async (url) => {
        const res =
            await fetch(
                url,
                createFetchOptions('GET'),
            );
        return res;
    },

    post: async (url, body) => {
        const res =
            await fetch(
                url,
                createFetchOptions('POST', body),
            );
        return res;
    },
}

router.post('/token', async (req, res) => {
    const { clientId, clientSecret, sessionCode } = req.body;

    const response = await Fetcher.post('https://github.com/login/oauth/access_token', {
        client_id: clientId,
        client_secret: clientSecret,
        code: sessionCode,
    });

    const result = await response.json();
    console.log(result)
    res.json(result);
});


module.exports = router;

最佳答案

您提供的代码似乎缺少您 request the user's GitHub identity 的步骤通过发出 GET https://github.com/login/oauth/authorize 请求。我假设您确实在代码中的某个位置包含此调用,因为有必要接收您在 POST https://github.com/正文中传递的 sessionCode 值login/oauth/access_token 请求。

无论如何,您都可以在这一步指定 the various scopes您的应用程序要求的。请求的范围通过 scope 查询参数传递,如果您请求多个范围,则以空格分隔。例如,以下是针对 userpublic_repo 范围的请求:

GET https://github.com/login/oauth/authorize?
  client_id=...&
  scope=user%20public_repo

关于javascript - GitHub API 的响应未返回具有适当范围的访问 token 来查看私有(private)存储库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55213669/

相关文章:

javascript - 转到 # 超链接上的特定选项卡 (accordin)

java - Java 中的 RESTful web 服务,用于下载压缩文件、解压缩并将 PDF 文件显示给客户端

java - Hazelcast REST API

c# - 如何在每分钟循环一次Powershell直到条件成立?

javascript - 无法使用 express.static 提供 json 文件

javascript - 将大 div 适合小 div 并保持比率 : absolute elements

从字符串中拆分并返回值的 Javascript 函数

api - 用于添加/删除数组元素的 RESTful API 端点?

java - 在Netbean中使用unirest发送短信

ios - Swift 5:解码嵌套JSON