ftimo-simple-jwt
v1.0.4
Published
This is a lightweight JavaScript library for working with JSON Web Tokens (JWT). It provides a minimal set of functions for encoding and decoding JWTs using the HS256 algorithm.
Downloads
11
Readme
Simple JWT Library
This is a lightweight JavaScript library for working with JSON Web Tokens (JWT). It provides a minimal set of functions for encoding and decoding JWTs using the HS256 algorithm.
Functions
1. base64urlEncode
Description: This function is used to encode a string using base64url encoding.
Usage:
const encodedString = base64urlEncode('your_string');
Returns:
- encodedString: A string representing the base64url-encoded input string.
2. createJWT
Description: Generates a JWT token based on the provided payload and secret.
Usage:
const payload = { user: 'john.doe', role: 'admin' };
const secretKey = 'your_secret_key';
const jwtToken = createJWT(payload, secretKey);
Returns:
- jwtToken: A string representing the generated JWT token.
3. validateJWT
Description: Validates a JWT token and returns the payload if the token is valid. If the token is invalid, it throws an error.
Usage:
const jwtToken = 'your_jwt_token';
const secretKey = 'your_secret_key';
try {
const decodedPayload = validateJWT(jwtToken, secretKey);
console.log('Decoded Payload:', decodedPayload);
} catch (error) {
console.error('Error:', error.message);
}
Returns:
- decodedPayload: An object representing the payload of the validated JWT token.
4. validateJWTFalseIfFail
Description: Validates a JWT token and returns the payload if the token is valid. If the token is invalid, it returns 'false' instead of throwing an error.
Usage:
const jwtToken = 'your_jwt_token';
const secretKey = 'your_secret_key';
const decodedPayload = validateJWTFalseIfFail(jwtToken, secretKey);
console.log('Decoded Payload:', decodedPayload);
Returns:
- decodedPayload: An object representing the payload of the validated JWT token if valid, or false if invalid.
Example
const {base64urlEncode, createJWT, validateJWTFalseIfFail,validateJWT} = require('ftimo-simple-jwt')
const payload = { user: 'john.doe', id: 7};
const secretKey = 'your_secret_key';
console.log(base64urlEncode("https://www.npmjs.com/package/ftimo-simple-jwt"))
// Create JWT
const jwtToken = createJWT(payload, secretKey);
console.log('JWT Token:', jwtToken);
// Validate JWT
try {
const decodedPayload = validateJWT(jwtToken, secretKey);
console.log('Decoded Payload:', decodedPayload);
} catch (error) {
console.error('Error:', error.message);
}
// Validate JWT and return false if invalid
const isValid = validateJWTFalseIfFail(jwtToken, 'wrong_secret_key');
console.log('Is Valid:', isValid);
Please replace 'your_string', 'your_secret_key', and 'your_jwt_token' with your actual values in the code examples.