Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 不正确的base64url_Node.js - Fatal编程技术网

Node.js 不正确的base64url

Node.js 不正确的base64url,node.js,Node.js,这里的JWT指南--说他们在这上面运行base64url: { "typ": "JWT", "alg": "HS256" } 他们的结局是: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 我尝试以下代码: var b64u = require("base64url") var rez = b64u(JSON.stringify({ "typ": "JWT", "alg": "HS256" })); var shouldbe = 'e

这里的JWT指南--说他们在这上面运行
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);
如在线测试中所示:

然而,它们并不匹配


有人看到任何简单的问题吗?

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

我认为他们的例子是错误的。我还得到了
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9
。附带说明,您不需要使用
base64url
模块对base64进行编码。只需执行
newbuffer(str).toString('base64');,其中
str`是您的字符串化JSON。很有趣,谢谢@dvlsgOh您知道吗,我想知道
JSON.stringify
是否正在切换
alg
typ
键的顺序。我注意到scotch.io教程中没有按字母顺序排列。当我使用一个字符串时,我得到了
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
,该字符串首先是
alg
,然后是
typ
。也来看看。它们对JWT的每一部分都进行了细分。非常感谢@dvlsgI,我想很多时候库/指南都会意外地认为,对象键不保证以任何方式进行排序这一事实是理所当然的。这里有另一个更详细的例子。