通过 Github API 获取令牌

Get a token by Github API

我在 Github -> Settings -> Personal access tokens -> Generate new token 中手动创建了一个令牌,并且只选择了 repo scope

这个令牌工作正常,所以我可以用它进入我拥有 write 特权的组织。

然后我想通过 github-api 做同样的事情(得到一个 access_token)。

params = dict(client_id=client_id,
              client_secret=client_secret,
              code=code)

url = url_concat("https://github.com/login/oauth/access_token", params)

req = HTTPRequest(url,
                  method="POST",
                  headers={"Accept": "application/json"},
                  body="") 

结果我有这样的 json:

{
    'scope': 'repo',
    'token_type': 'bearer',
    'access_token': 'xxxxxxxx10755fbb6c281e92902ed122144886c5'
}

一切都是正确的,但我无法进入我拥有 write 权限的组织存储库。我只能推送到我自己的仓库中。

你能帮忙吗?欢迎任何错误或不准确的想法。

因此,如果您想通过 GitHub 的 API 执行此操作,您的请求需要更改。

首先你需要像这样使用 /authorizations endpoint:

POST /authorizations
Authorization: Basic ...
Content-Type: application/json
Content-Length: ...

{
  "scopes": [
    "repo",
    "write:org"
  ],
  "note": "Example from Whosebug by @sigmavirus24",
  "client_id": "Your client_id here",
  "client_secret": "Your client_secret here",
  "fingerprint": "1234",
}

这应该 return 一个 201 Created 响应,正文如下:

{
  "id": 72249124,
  "url": "https://api.github.com/authorizations/72249124",
  "scopes": [
    "repo",
    "write:org"
  ],
  "token": "abcdefgh12345678",
  "token_last_eight": "12345678",
  "hashed_token": "25f94a2a5c7fbaf499c665bc73d67c1c87e496da8985131633ee0a95819db2e8",
  "app": {
    "url": "http://my-github-app.com",
    "name": "my github app",
    "client_id": "abcde12345fghij67890"
  },
  "note": "optional note",
  "note_url": "http://optional/note/url",
  "updated_at": "2017-02-08T20:39:23Z",
  "created_at": "2017-02-08T17:26:27Z",
  "fingerprint": "1234"
}

除非它是真实的。

也就是说,您似乎正在尝试使用允许 GitHub 用作身份验证提供程序的端点。换句话说,您正在构建一个允许用户 sign-in 和 GitHub 的应用程序。如果是这种情况,那么您需要专门遵循 Web Application Flow for OAuth.

在那种情况下,你是路途中的一部分,但你发送了错误的参数。

首先你发出一个 GET 请求:

GET https://github.com/login/oauth/authorize?client_id=<your-client_id>&scopes=repo%20write:org&state=something-random

然后您将从 GitHub 收到您必须在 POST

中使用的数据
POST https://github.com/login/oauth/access_token?client_id=<your-client_id>&client_secret=<your-client_secret>&code=<code-from-github>
Accept: application/json

之后,您提出的任何要求都必须

Authorization: token <token-received-in-response-to-POST>

干杯!

通过在基本授权[=]中传递您的client_idclient_secret,将POST与urlhttps://api.github.com/authorizations一起使用18=]。 将其余参数以 json 格式发送到正文中作为原始参数。
例如:

{
  "scopes": 
    [
      "repo",
      "write:org"
    ],
  "note": "Sample Access Token using API Call",
  "fingerprint": "DEMO#@A"
}