yajwt v1.5.5
yajwt
An implementation of JSON Web Tokens.
This was developed against draft-ietf-oauth-json-web-token-08. It makes use of node-jws and has heavily used jsonwebtoken module as inspiration
Install
$ npm install yajwtUsage
jwt.sign(options, callback)
(Asynchronous) Callback has err, JWT string signature
jwt.signSync(options)
(Synchronous) Returns an object with an error(on failure) and token property (on success)
options:
headerobject with following propertiesalgdefault:RS256typdefault 'JWT', this is only accepted value for this property
payload: object with the following propertiesaud: string - audience of tokenexp: number ms since EPOCH or a string describing a time duration added to seconds since EPOCH rauchg/ms. Eg:60,"2 days","10h","7d"or Moment formats types 'DD-MM-YYYY', 'DD-MM-YY', 'DD/MM/YYYY', 'DD/MM/YY'iat: same as above, defaults to the time payload is signed. If duration is used the value is added to Date.now()iss: string - issuer of tokenjti: string - unique identity of tokennbf: same as expsub: string - describing subject of token
privateKey: string or buffer of private key to sign token
All timestamp related fields if a number are coerced into seconds from ms.
Additional custom header properties can be provided via the header object.
Example
const jwt = require('yajwt');
// read key for signing
const key = fs.readFileSync('private.pem');
const signed = jwt.signSync({ header: { alg: 'HS256' }, payload: {aud: 'private'}, privateKey: key });
console.log(signed.token); /// prints JWT string
// sign asynchronously
jwt.sign({ header: { alg: 'HS256' }, payload: {aud: 'private'}, privateKey: key }, (err, token) => {
console.log(err, token);
});jwt.verify(options, callback)
(Asynchronous) Callback has err, decoded JWT signature
jwt.verifySync(options)
(Synchronous) Returns true or false depending on whether token can be verified as valid
options
algorithmsdefault: RS256.signaturejson string to verifypublicKey: is a string or buffer containing either the secret for HMAC algorithms, or the PEM encoded public key for RSA and ECDSA.
// verify a token asymmetric
const publicKey = fs.readFileSync('public.pem'); // get public key
const valid = jwt.verifySync(token, publicKey);
console.log(valid) // true
// verify a token symmetric
jwt.verify({signature: jsonString, algorithm: 'HS256', publicKey: publicKey}, (err, decoded) => {
console.log(err) // null
console.log(decoded) // decoded token meaning payload verified
});Todo
- improve error handling for missing callback on async funcs
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago