[英]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.