shJWT is a simple library designed to offer JSON Web Token (JWT) encoding and decoding functions, using HMAC with SHA256 for signing. The library is lightweight, secure, and adheres to best practices for JWT usage.
Install via npm:
npm install --save shjwt
Use the library by requiring it and calling the encode
and decode
functions.
const shjwt = require('shjwt');
const secret = 'a_secure_and_long_secret_key_that_is_at_least_32_chars';
const payload = {
user_id: 1,
email: 'test@example.com',
exp: Math.floor(Date.now() / 1000) + 3600 // Token expires in 1 hour
};
shjwt.encode(payload, secret)
.then(jwt => console.log(jwt)) // prints the encoded JWT
.catch(err => console.error(err));
const jwt = 'your.jwt.token.here';
shjwt.decode(jwt, secret)
.then(decodedPayload => console.log(decodedPayload)) // prints the decoded payload
.catch(err => console.error(err));
Converts the provided payload into a JWT.
-
payload
(Object): The payload that will be encoded. You can include standard claims likeexp
(expiration). -
secret
(string): A secret key with a minimum length of 32 characters for generating the HMAC. - Returns a Promise that resolves with the JWT token.
Throws:
- Error if the secret key is too short.
- Error if encoding fails.
Decodes the JWT into the original payload and verifies its signature.
-
jwt
(string): The JWT to be decoded. -
secret
(string): The secret key for verifying the HMAC. - Returns a Promise that resolves with the decoded payload.
Throws:
- Error if the token has expired.
- Error if the token signature is invalid.
- Error if the token format is incorrect.
- Error if the algorithm in the header is unsupported.
- Secure Signature Verification: Uses constant-time comparison to prevent timing attacks.
-
Expiration Handling: Tokens with an
exp
claim are automatically validated. - Algorithm Validation: Supports only HS256 to prevent algorithm substitution attacks.
- Strong Key Enforcement: Requires secret keys to be at least 32 characters long.
To test, ensure you have installed the necessary development dependencies:
npm install --dev
Run tests with:
npm test
Please use this library responsibly and ensure that you understand security best practices for JWT usage. Always use a secure, randomly generated secret key and validate claims appropriately.
If you'd like to contribute, please fork the repository and use a feature branch. All contributions are welcome and greatly appreciated.