Created
December 26, 2024 12:34
-
-
Save Mr-emeka/b6355a8897c90e8760ecac4b1dd4972e to your computer and use it in GitHub Desktop.
How to Generate JWT Token in React Native
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Base64 from 'crypto-js/enc-base64'; | |
import Utf8 from 'crypto-js/enc-utf8'; | |
import HmacSHA256 from 'crypto-js/hmac-sha256'; | |
export async function generateJWT( | |
header: any, | |
payload: any, | |
secret: string, | |
) { | |
// Step 1: Base64Url encode header and payload | |
const jsonHeader = Base64.stringify(Utf8.parse(JSON.stringify(header))); | |
const jsonPayload = Base64.stringify(Utf8.parse(JSON.stringify(payload))); | |
const base64Header = urlEncodeBase64(jsonHeader); | |
const base64Payload = urlEncodeBase64(jsonPayload); | |
// Step 2: Create the message to sign | |
const message = `${base64Header}.${base64Payload}`; | |
// Step 3: Sign the message using HMAC SHA256 with the secret key | |
const signature = HmacSHA256(message, secret); | |
const base64Signature = signature.toString(Base64); | |
// Step 4: Base64Url encode the signature | |
const base64UrlSignature = urlEncodeBase64(base64Signature); | |
console.log(`${base64Header}.${base64Payload}.${base64UrlSignature}`); | |
// Step 5: Combine the parts to create the JWT | |
return `${base64Header}.${base64Payload}.${base64UrlSignature}`; | |
} | |
export const urlEncodeBase64 = (signature: string): string => { | |
signature = signature.replace(/(=+)$/g, ''); | |
signature = signature.replace(/\//g, '_'); | |
signature = signature.replace(/\+/g, '-'); | |
return signature; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment