0.0.4 • Published 10 years ago

jwthelper v0.0.4

Weekly downloads
279
License
MIT
Repository
github
Last release
10 years ago

jwthelper

An easy to use helper class for jsonwebtoken.

Install

npm install jwthelper --save

Usage

var JWTHelper = require('jwthelper');
var helper = JWTHelper.createJWTHelper([options]);

options needs to have a secret or privateKey field, otherwise an error will be returned.

options:

  • algorithm: an algorithm for signing supported by jsonwebtoken (default HS512)
  • secret: a string containing the secret to encode the token with
  • privateKey: a private key to encode the token with
  • expiresInMinutes or expiresInSeconds: set jwt expiration
  • noTimestamp: omit the timestamp in the jwt payload
  • ignoreExpiration: ignore expiration settings when verifying a jwt
  • audience: set the audience for signing and verifying
  • issuer: set the issuer for signing and verifying
  • subject: set the subject for signing and verifying
  • headers: an optional array containig header fields

All these options can also be used in the methods below.

var jwt = helper.sign(payload[, signOptions]);

Signs a JWT which has the payload payload. The optional signOptions accept all options mentioned above and will be used for this signing only.

helper.verify(token, [verifyOptions, ]callback);

Verifies a token. The callback conforms to the standard (error, payload) scheme. verifyOptions accepts all options mentioned above and will be used for this verification only.

var decoded = helper.decode(token[, decodeOptions]);

Convenience method for jwt.decode. Decodes the token without validating it.

decodeOptions:

  • json: force JSON.parse on the payload even if the header doesn't contain "typ":"JWT" (jsonwebtoken)
  • complete: return an object with the decoded payload and header (jsonwebtoken)
helper.setOptions(options);

Updates the options for the helper. The options array accepts all parameters mentioned above.

Example

var JWTHelper = require('jwthelper');

// Create a new helper and set the options for that helper
var helper = JWTHelper.createJWTHelper({
    'secret': 'this is my secret'
});

// Signing a JWT
var jwt = helper.sign({
    '_id': 55,
    'isAdmin': true
});

// This outputs the signed JWT
console.log(jwt);

// Now we are going to decode it!
helper.verify(jwt, function(err, decoded) {
    if(err) return console.log((err.name == 'JsonWebTokenError') ? 'Invalid token' : err.name);
    // And we display the decoded JWT
    console.log(decoded);
});

Version history

  • 0.0.3 - 12 July 2015
    • Added helper.decode convenience method
  • 0.0.1, 0.0.2 - 12 July 2015
    • First release

License

Copyright 2015 Michiel van der Velde.

This software is licensed under the MIT License