智威汤逊指南 - https://scotch.io/tutorials/the-anatomy-of-a-json-web-token#header - 说他们对此运行base64url
:
{
"typ": "JWT",
"alg": "HS256"
}
他们最终会得到这样的结果:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
我尝试这段代码:
var b64u = require("base64url")
var rez = b64u(JSON.stringify({
"typ": "JWT",
"alg": "HS256"
}));
var shouldbe = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9';
console.log(rez);
console.log(shouldbe);
console.log(rez == shouldbe);
如在线测试所示: https://tonicdev.com/56c5484d7a4ea10d0002c623/5733af59234d9d1200d8c818
但是它们不匹配。
有人看到任何简单的问题吗?
最佳答案
Base64 输出取决于您在 JSON.stringify
调用中收到的字符串中键的顺序。
下面是一个使用预构建 JSON 字符串的工作示例,供引用。
let expected = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9';
let str1 = '{"alg":"HS256","typ":"JWT"}';
let str2 = '{"typ":"JWT","alg":"HS256"}';
// note that you don't need a library to Base64 encode strings in node
let base64str1 = new Buffer(str1).toString('base64');
let base64str2 = new Buffer(str2).toString('base64');
console.log(base64str1); // 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9'
console.log(base64str2); // 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9'
console.log('base64str1 equals expected?', base64str1 === expected); // true
console.log('base64str2 equals expected?', base64str2 === expected); // false
关于node.js - base64url 不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37174233/