Getting access token from Github

天涯浪子 提交于 2019-12-07 00:35:31

I got this working. It's largely based on what you have but there are a few tweaks:

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();

The main issue for me was with the private_key variable got generated. Alos, I changed 600 to (10 * 60) as I had got a different error at one stage of my investigation but that turned out to not be the problem. It doesn't really matter what you have there so I left it.

The other change I made was to assign axios to a variable. I'm relatively new to node.js so not really sure why this had to be done but suspect its something to do with the synchronous/asynchronous aspect of node.js.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!