首页 > 解决方案 > GitHub API 401 Node 中的错误凭证但不是 curl

问题描述

我正在尝试使用@octokit/rest. 如果我使用以下 Curl,我会得到 API 的 URL 列表:

curl -u "my@email.com" https://api.github.<my domain>.com

当我运行它时,系统会提示我输入密码,在其中输入我的个人访问令牌。

但是,如果我在节点应用程序中使用相同的详细信息,我会收到 401 Bad Credentials 响应。这就是我配置身份验证的方式:

octokit.authenticate({
  baseUrl: 'https://api.github.<my domain>.com', 
  type: 'basic',
  username: 'my@email.com',
  password: '<my personal access token>'
});

根据文档,我认为这应该可行。任何人都可以告诉为什么它没有?

这是我得到的完整 HTTP 响应:

{ HttpError: {"message":"Bad credentials","documentation_url":"https://developer.github.com/v3"}
    at response.text.then.message (/node_modules/@octokit/rest/lib/request/request.js:72:19)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)
  name: 'HttpError',
  code: 401,
  status: undefined,
  headers: 
   { 'access-control-allow-origin': '*',
     'access-control-expose-headers': 'ETag, Link, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval',
     connection: 'close',
     'content-length': '83',
     'content-security-policy': 'default-src \'none\'',
     'content-type': 'application/json; charset=utf-8',
     date: 'Mon, 10 Sep 2018 13:20:12 GMT',
     'referrer-policy': 'origin-when-cross-origin, strict-origin-when-cross-origin',
     server: 'GitHub.com',
     status: '401 Unauthorized',
     'strict-transport-security': 'max-age=31536000; includeSubdomains; preload',
     'x-content-type-options': 'nosniff',
     'x-frame-options': 'deny',
     'x-github-media-type': 'github.v3; format=json',
     'x-github-request-id': 'C8BA:76CE:24B2BB3:45F82A2:5B966F8B',
     'x-ratelimit-limit': '10',
     'x-ratelimit-remaining': '9',
     'x-ratelimit-reset': '1536585672',
     'x-runtime-rack': '0.039959',
     'x-xss-protection': '1; mode=block' } }

附加信息

这似乎是我的问题发生的地方:

let response = await method({
    q: "repo:" + repoOrg + "/" + repoName + " is:issue",
    per_page: 100
  });

这类似于 npm 页面上的示例。身份验证是否可能在某种程度上没有得到应用,如果是这样,我如何确保它确实得到应用?

标签: javascriptnode.jsgithubgithub-apigithub-api-v3

解决方案


为了使用令牌进行身份验证,您应该将身份验证类型设置为token生成令牌

username同时接受电子邮件和用户名

完整的工作示例:

const octokit = require('@octokit/rest')();

octokit.authenticate({
  type: 'token',
  username: 'my username',
  token: 'my token'
});

octokit.activity.getStarredRepos().then(results => {
  console.log(results);
});

推荐阅读