Created
November 10, 2023 19:24
-
-
Save chardcastle/d76347c2f5c2f7584ee132425495891a to your computer and use it in GitHub Desktop.
JWT Sign and Verify - good for API and APP respectfully. Where jsonwebtoken was buggy on client side
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
/** | |
* Example output | |
* | |
* # node user/jwt.js | |
* Generated JWT: eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNjk5NjQ0MTczLCJleHAiOjE2OTk2NDc3NzMsImlzcyI6InVybjpleGFtcGxlOmlzc3VlciIsImF1ZCI6InVybjpleGFtcGxlOmF1ZGllbmNlIn0.qkYazhX0__WeBAjiW1MvXndqdBc4qsP-mX8vWIzCPwE | |
* Verified Payload: { | |
* sub: '1234567890', | |
* name: 'John Doe', | |
* iat: 1699644173, | |
* exp: 1699647773, | |
* iss: 'urn:example:issuer', | |
* aud: 'urn:example:audience' | |
* } | |
* Verified protectedHeader: { alg: 'HS256' } | |
*/ | |
import * as jose from 'jose'; | |
const payload = { | |
sub: '1234567890', | |
name: 'John Doe', | |
iat: Math.floor(Date.now() / 1000), // Issued At Time | |
exp: Math.floor(Date.now() / 1000) + 60 * 60, // Expiration Time (1 hour) | |
}; | |
const secret = new TextEncoder().encode( | |
"secretSausage" | |
); | |
const jwt = await new jose.SignJWT(payload) | |
.setProtectedHeader({ alg: "HS256" }) | |
.setIssuer('urn:example:issuer') | |
.setAudience('urn:example:audience') | |
.sign(secret); | |
console.log('Generated JWT:', jwt); | |
try { | |
const { payload, protectedHeader } = await jose.jwtVerify(jwt, secret, { | |
issuer: 'urn:example:issuer', | |
audience: 'urn:example:audience', | |
}) | |
console.log('Verified Payload:', payload); | |
console.log('Verified protectedHeader:', protectedHeader); | |
} catch (error) { | |
console.error('JWT Verification Failed:', error.message); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment