Skip to content

Instantly share code, notes, and snippets.

@helton
Created May 3, 2021 21:29
Show Gist options
  • Save helton/133c3a69de7a4533ff7c2b12d59ed00e to your computer and use it in GitHub Desktop.
Save helton/133c3a69de7a4533ff7c2b12d59ed00e to your computer and use it in GitHub Desktop.
JWT with HS256 (HMAC SHA-256) algorithm in JS
function base64UrlEncode(str) {
return btoa(str).replace('+', '-').replace('/', '_').replace(/=+$/, '');
}
async function HMACSHA256(key, message){
const g = str => new Uint8Array([...unescape(encodeURIComponent(str))].map(c => c.charCodeAt(0))),
k = g(key),
m = g(message),
c = await crypto.subtle.importKey('raw', k, { name: 'HMAC', hash: 'SHA-256' },true, ['sign']),
s = await crypto.subtle.sign('HMAC', c, m);
[...new Uint8Array(s)].map(b => b.toString(16).padStart(2, '0')).join('');
return base64UrlEncode(String.fromCharCode(...new Uint8Array(s)));
}
async function jwt(header, payload, key) {
const prefix = `${base64UrlEncode(JSON.stringify(header))}.${base64UrlEncode(JSON.stringify(payload))}`;
const suffix = await HMACSHA256(key, prefix);
return `${prefix}.${suffix}`;
}
//Example:
(async function() {
const header = {
'typ': 'JWT',
'alg': 'HS256'
};
const payload = {
'sub': 'helton',
'iss': 'my-company'
};
const key = 'my-very-secret-key';
console.log('jwt', await jwt(header, payload, key));
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment