繁体   English   中英

从 Github 获取访问令牌

[英]Getting access token from Github

我正在尝试使用 NodeJS 客户端从 Github 获取访问令牌。

const axios = require("axios");
var jwt = require("jsonwebtoken");

exports.openedPOST = function openedPOST(req, res) {

// generate jwt
const now = Math.round(Date.now() / 1000);
const payload = {
    // issued at time
    iat: now,
    // expires in 10min
    exp: now + 600,
    // Github app id
    iss: 6700
};

const token = jwt.sign(payload, cert, { algorithm: "RS256" });
console.log(token)

// auth to github
axios({
  method: "get",
  url: "https://api.github.com/app",
  headers: {
    Accept: "application/vnd.github.machine-man-preview+json",
    Authorization: `Bearer ${token}`
  }
})
.then(function(response) {
  console.log(response.data);
})
.catch(function(error) {
  console.warn("Unable to authenticate");
  // The request was made and the server responded with a status code
  // that falls out of the range of 2xx
  if (error.response) {
    console.warn(`Status ${error.response.status}`);
    console.warn(`${error.response.data.message}`);
  }
});

res.status(200).end();

但这只会产生: { "message": "A JSON web token could not be decoded", "documentation_url": "https://developer.github.com/v3" }

我已经在https://jwt.io验证了令牌,并且负载符合预期。

我得到了这个工作。 它主要基于您拥有的内容,但有一些调整:

const axios = require("axios");
var fs = require('fs');
var jwt = require("jsonwebtoken");


exports.openedPOST = function openedPOST(req, res) {

  // Private key contents
  var private_key = fs.readFileSync("/path/to/pemfile.pem");
  console.log("private_key: ", private_key);

  // generate jwt
  const now = Math.round(Date.now() / 1000);
  const payload = {
    // issued at time
    iat : now,
    // expires in 10min
    exp : now + (10 * 60),
    // Github app id
    iss : 7233
  };
  console.log("payload: ", payload);

  const token = jwt.sign(payload, private_key, { algorithm: 'RS256' })
  console.log("Token: ", token)

  // auth to github
  var instance = axios({
    method: "get",
    url: "https://api.github.com/app",
    headers: {
      "Accept" : "application/vnd.github.machine-man-preview+json",
      "Authorization" : `Bearer ${token}`
    }
  })
  .then(function(response) {
    console.log("Response: ",response.data);
  })
  .catch(function(error) {
    console.warn("Unable to authenticate");
    // The request was made and the server responded with a status code
    // that falls out of the range of 2xx
    if (error.response) {
      console.warn(`Status ${error.response.status}`);
      console.warn(`${error.response.data.message}`);
    }
  });
};
exports.openedPOST();

对我来说,主要问题是生成了 private_key 变量。 Alos,我将600更改为(10 * 60)因为我在调查的某个阶段遇到了不同的错误,但结果证明这不是问题。 你在那里有什么并不重要,所以我离开了它。

我所做的另一个更改是将axios分配给一个变量。 我对 node.js 比较陌生,所以不太确定为什么必须这样做,但怀疑它与 node.js 的同步/异步方面有关。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM