来自GitHub API的响应未返回具有适当范围的访问令牌以查看私有存储库

时间:2019-03-18 01:31:19

标签: javascript rest api

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

// githubs response

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

该令牌无法像启用范围的个人访问令牌那样查看私有存储库。我是在做错事还是没有联系正确的端点?

// 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;

1 个答案:

答案 0 :(得分:2)

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

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

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