Noitidart
Noitidart

Reputation: 37238

Improper base64url

The JWT guide here - https://scotch.io/tutorials/the-anatomy-of-a-json-web-token#header - says they run base64url on this:

{
  "typ": "JWT",
  "alg": "HS256"
}

And they end up with this:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9

I try this code:

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

as seen here in online test: https://tonicdev.com/56c5484d7a4ea10d0002c623/5733af59234d9d1200d8c818

however they are not matching.

Does anyone see any simple issue?

Upvotes: 1

Views: 2257

Answers (1)

dvlsg
dvlsg

Reputation: 5538

The Base64 output is dependent on which order of keys you receive in the string from the JSON.stringify call.

For reference, here is a working example using pre-built JSON strings.

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

Upvotes: 1

Related Questions