Skip to content

Instantly share code, notes, and snippets.

@blake-simpson
Last active July 11, 2023 15:33
Show Gist options
  • Save blake-simpson/0acc1eb4233e1b2edca9869edd6e335c to your computer and use it in GitHub Desktop.
Save blake-simpson/0acc1eb4233e1b2edca9869edd6e335c to your computer and use it in GitHub Desktop.
Generate JWT in Expo
import HmacSHA256 from 'crypto-js/hmac-sha256';
import Base64 from 'crypto-js/enc-base64';
import Utf8 from 'crypto-js/enc-utf8';
const header = {
alg: 'HS256',
typ: 'JWT'
};
const body = { foo: 'bar' };
const jsonHeader = JSON.stringify(header);
const jsonBody = JSON.stringify(body);
const headerEncoded = Base64.stringify(Utf8.parse(jsonHeader));
const bodyEncoded = Base64.stringify(Utf8.parse(jsonBody));
const key = 'shh';
const signature = HmacSHA256(`${headerEncoded}.${bodyEncoded}`, key);
const signatureEncoded = signature.toString(Base64);
const token = `${headerEncoded}.${bodyEncoded}.${signatureEncoded}`;
@HeavenMin
Copy link

Just passing through, you should also consider replacing the symbols that are unsafe to use in a URL: ' +', '/', and '='. Otherwise, your final encoded signature might be different.

@blake-simpson
Copy link
Author

Hi @HeavenMin, that’s a good point.

Do you have any examples where this has been an issue?

I just added a new test to the repo to try this out and so far the library seems to encode/decode as expected.

Cheers,
Blake

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment