0.5.0 • Published 5 years ago

jwtr v0.5.0

Weekly downloads
40
License
MIT
Repository
github
Last release
5 years ago

JWTR

It's a little wrapper over Json Web Tokens and Redis for Node.js is based on promises.

Install

npm package

$ npm install jwtr --save

yarn package

$ yarn add jwtr

Usage

const JWTR = require('jwtr')
const token = JWTR.sign({ foo: 'bar' }, 'secret', { expiresIn: '1h' })
const decoded = JWTR.verify(token, 'secret')
const completeDecoded = JWTR.decode(token, {complete: true})

JWTR provides full Json Web Tokens's interface with exceptions. See more details.

Also JWTR provides redis's client interface via property client.

const JWTR = require('jwtr')
const jwtr = JWTR.createJWTR({
    prefix: 'token_'
})
jwtr.client.on('connect', () => {
    console.log('Connected!')
})

See more details.

For JWT via Redis was implemented next methods:

Returns true if token was successfully stored in redis.

token is the JsonWebToken string

const JWTR = require('jwtr')
const jwtr = JWTR.createJWTR({
    prefix: 'token_'
})
const token = JWTR.sign({ foo: 'bar' }, 'secret', { expiresIn: '1h' })
const result = await jwtr.invalidate(token) // true

(Asynchronous) If a callback is supplied, function acts asynchronously. The callback is called with the decoded payload if the signature is valid and optional expiration, audience, or issuer are valid. If not, it will be called with the error.

(Synchronous) If a callback is not supplied, function acts synchronously. Returns the payload decoded if the signature is valid and optional expiration, audience, or issuer are valid. If not, it will throw the error.

token is the JsonWebToken string

secretOrPublicKey is a string or buffer containing either the secret for HMAC algorithms, or the PEM encoded public key for RSA and ECDSA.

options

  • algorithms: List of strings with the names of the allowed algorithms. For instance, ["HS256", "HS384"].
  • audience: if you want to check audience (aud), provide a value here. The audience can be checked against a string, a regular expression or a list of strings and/or regular expressions.

    Eg: "urn:foo", /urn:f[o]{2}/, [/urn:f[o]{2}/, "urn:bar"]

  • issuer (optional): string or array of strings of valid values for the iss field.
  • ignoreExpiration: if true do not validate the expiration of the token.
  • ignoreNotBefore...
  • subject: if you want to check subject (sub), provide a value here
  • clockTolerance: number of seconds to tolerate when checking the nbf and exp claims, to deal with small clock differences among different servers
  • maxAge: the maximum allowed age for tokens to still be valid. It is expressed in seconds or a string describing a time span zeit/ms.

    Eg: 1000, "2 days", "10h", "7d". A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc), otherwise milliseconds unit is used by default ("120" is equal to "120ms").

  • clockTimestamp: the time in seconds that should be used as the current time for all necessary comparisons.
  • nonce: if you want to check nonce claim, provide a string value here. It is used on Open ID for the ID Tokens. (Open ID implementation notes)

jwtr.validate and jwt.verify is the same, but also validate's method checks redis's store for invalid tokens.

const JWTR = require('jwtr')
const jwtr = JWTR.createJWTR({
    prefix: 'token_'
})
const token = JWTR.sign({ foo: 'bar' }, 'secret', { expiresIn: '1h' })
const decoded = await jwtr.validate(token, 'secret', { algorithms: ['HS256'] })

Returns new access and refresh tokens beforehand making old tokens not valid.

tokens:

  • accessToken is the JsonWebToken string
  • refreshToken is the JsonWebToken string

secretOrPrivateKey is a string, buffer, or object containing either the secret for HMAC algorithms or the PEM encoded private key for RSA and ECDSA. In case of a private key with passphrase an object { key, passphrase } can be used (based on crypto documentation), in this case be sure you pass the algorithm option.

options:

  • access_payload (optional) could be an object literal, buffer or string representing valid JSON.
  • refresh_payload (optional) could be an object literal, buffer or string representing valid JSON.
  • access_options (optional):
    • algorithm (default: HS256)
    • expiresIn: expressed in seconds or a string describing a time span zeit/ms.

      Eg: 60, "2 days", "10h", "7d". A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc), otherwise milliseconds unit is used by default ("120" is equal to "120ms").

    • notBefore: expressed in seconds or a string describing a time span zeit/ms.

      Eg: 60, "2 days", "10h", "7d". A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc), otherwise milliseconds unit is used by default ("120" is equal to "120ms").

    • audience
    • issuer
    • jwtid
    • subject
    • noTimestamp
    • header
    • keyid
    • mutatePayload: if true, the sign function will modify the payload object directly. This is useful if you need a raw reference to the payload after claims have been applied to it but before it has been encoded into a token.
  • refresh_options (optional)
    • algorithm (default: HS256)
    • expiresIn: expressed in seconds or a string describing a time span zeit/ms.

      Eg: 60, "2 days", "10h", "7d". A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc), otherwise milliseconds unit is used by default ("120" is equal to "120ms").

    • notBefore: expressed in seconds or a string describing a time span zeit/ms.

      Eg: 60, "2 days", "10h", "7d". A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc), otherwise milliseconds unit is used by default ("120" is equal to "120ms").

    • audience
    • issuer
    • jwtid
    • subject
    • noTimestamp
    • header
    • keyid
    • mutatePayload: if true, the sign function will modify the payload object directly. This is useful if you need a raw reference to the payload after claims have been applied to it but before it has been encoded into a token.
const JWTR = require('jwtr')
const jwtr = JWTR.createJWTR({
    prefix: 'token_'
})
const accessToken = JWTR.sign({ foo: 'bar' }, 'secret', { expiresIn: '15m' })
const refreshToken = JWTR.sign({ foo: 'bar' }, 'secret', { expiresIn: '2h' })
let { access_token, refresh_token } = await jwtr.refresh(
    { accessToken, refreshToken },
    'secret',
    {
        access_payload: { foo: 'bar' },
        refresh_payload: { foo: 'bar' }
    }
)

Also functions to clear tokens from redis

Clear all expired tokens from redis.

const JWTR = require('jwtr')
const jwtr = JWTR.createJWTR({
    prefix: 'token_'
})
await jwtr.clear()

Clear all tokens from redis.

const JWTR = require('jwtr')
const jwtr = JWTR.createJWTR({
    prefix: 'token_'
})
await jwtr.clearAll()

And helpers functions

Set object by key in redis.

const JWTR = require('jwtr')
const jwtr = JWTR.createJWTR({
    prefix: 'token_'
})
await jwtr.set('token', { foo: 'bar'})

Get object by key from redis.

const JWTR = require('jwtr')
const jwtr = JWTR.createJWTR({
    prefix: 'token_'
})
await jwtr.get('token')

Method provides access to keys from redis and performs callback with keys.

const JWTR = require('jwtr')
const jwtr = JWTR.createJWTR({
    prefix: 'token_'
})
await jwtr.keys(keys => {
    console.log(keys)
})

Method executes a provided function once for each array of the keys item.

const JWTR = require('jwtr')
const jwtr = JWTR.createJWTR({
    prefix: 'token_'
})
await jwtr.forEachKey(key => {
    console.log(key)
})

Delete all the keys. See more details.

const JWTR = require('jwtr')
const jwtr = JWTR.createJWTR({
    prefix: 'token_'
})
await jwtr.flush()

Dependencies

Issue Reporting

If you have found a bug or if you have a feature request, please report them at this repository issues section.

ToDo

Show project JWTR

Contact me

CHANGELOG

LICENSE

Copyright (c) 2019 Ivan Monastyrev ikloster@yandex.ru. Licensed under the MIT license.

0.5.0

5 years ago

0.4.0

5 years ago

0.3.6

5 years ago

0.3.5

5 years ago

0.3.4

5 years ago

0.3.3

5 years ago

0.3.2

5 years ago

0.3.1

5 years ago

0.3.0

5 years ago

0.2.6

5 years ago

0.2.5

5 years ago

0.2.4

5 years ago

0.2.3

5 years ago

0.2.2

5 years ago

0.2.1

5 years ago

0.2.0

5 years ago

1.0.0

7 years ago