1.0.9 β€’ Published 5 years ago

@samespace/token-service-koa v1.0.9

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

πŸ”ŒToken Service (Koa Middleware)

npm version code cov CircleCI Dependencies Known Vulnerabilities

Table of Contents

Getting started

Install @samespace/token-service-koa using npm.

# NPM
npm install @samespace/token-service-koa --save

# YARN
yarn add @samespace/token-service-koa

Obtaining Service Account

Service accounts can be obtained by raising a request at Selfcare

Documentation

Token Service API documentation can be found here.

Usage

TokenService middleware should be the first middleware after any bod-parser

const Koa = require('koa');
const app = new Koa();

const TokenService = require('@samespace/token-service-koa');
const TokenServiceMiddleware = new TokenService({
  path: '/TokenService',
  audience: 'https://exmaple.com/TokenService',
  keyFile: './serviceAccount.json'
});

app.use(TokenServiceMiddleware);

app.use(async ctx => {
  ctx.body = 'Hello World';
});

app.listen(3000);

Arguments

ArgumentTypeDescriptionRequired
pathStringPath at which the middleware will listen for Token Server requests.βœ”οΈ
audienceStringAudience against which tokens will be verified.βœ”οΈ
keyFileString | ObjectPath from root of service account file or Object containing service account configuration.βœ”οΈ
ignorePathsArrayArray of paths or regular expression to ignore AuthenticationE.g: ignorePaths: ['/login', /\/(about-us\|contact)/]This will skip authentication on path /login and any path containing the keywords about-us or contact❌
tokenTtlIntegerTTL of the token to be validated locally, after expiry a verifyToken call will be made.❌
onRedirectFunctionFunction to trigger when token is not provided by the client and redirection to redirect_uri needs to be overridden.❌
onExpiryFunctionFunction to trigger when an expired token is provided by the client.❌
onDeauthorizeFunctionFunction to trigger when a token is forcefully deauthorized by an audience scope.❌
onErrorFunctionFunction to trigger when an unhandled error has occured.❌

Reference

onRedirect

Default:

// Deafult will redirect user to redirect_uri

Usage:

new TokenService({
  onRedirect: (ctx) => {
    ctx.redirect('/login')
  }
})

onExpiry

Default:

new TokenService({
  onExpiry: (err, ctx) => {
    ctx.status = 401
    ctx.body = {
      code: 401,
      msg: 'TOKEN_EXPIRY',
      service: 'TokenService'
    }
  }
})

Usage:

new TokenService({
  onExpiry: (err, ctx) => {
    // Log err to console
    ctx.logger.error(err)
        
    // Set status for client
    ctx.status = 401
  }
})

onDeauthorize

Default:

new TokenService({
  onDeauthorize: () => {}
})

Usage:

new TokenService({
  onDeauthorize: (ctx, deauthorizeToken) => {
    // Log err to console
    ctx.logger.info(`Deauthorized token: ${deauthorizeToken}`)
  }
})

onError

Default:

new TokenService({
  onError: (err, ctx) => {
    console.error(err)
    ctx.status = 500
    ctx.body = {
      code: 500,
      msg: 'INTERNAL_SERVICE_ERROR',
      service: 'TokenService'
    }
  }
})

Usage:

new TokenService({
  onError: (err, ctx) => {
    // Log err to console
    ctx.logger.error(err)
        
    // Set status for client
    ctx.status = 500
  }
})

Helper Functions

These functions can be used to provide additional functionalities. For ease, they are binded to ctx.tokenService.

ctx.tokenService.generateToken(String, String)

/*
 * @async
 * @param {string} subject - Subject for the JWT Token
 * @param {string} claims - JWT Token private claim
 * @return {Promise<string>}
**/
ctx.tokenService.generateToken(subject, claims).then(({ subject, token }) => {
  // ...do something with token
}).catch(err => {
  // ...error handling
})

Rejections:

{
  name: 'TokenServiceError',
  message: 'INVALID_SUBJECT'
}
{
  name: 'TokenServiceError',
  message: 'INVALID_PAYLOAD'
}
{
  name: 'TokenServiceError',
  message: 'INVALID_ACCOUNT_CREDENTIALS'
}
{
  name: 'TokenServiceError',
  message: 'SERVER_ERROR'
}

ctx.tokenService.verifyToken(String)

/*
 * @async
 * @param {string} token - JWT Token to verify
 * @return {Promise<string>}
**/
ctx.tokenService.verifyToken(token).then(() => {
  // Token Verified
}).catch(err => {
  // ...error handling
})

Rejections:

{
  name: 'TokenServiceError',
  message: 'INVALID_KEY_ID'
}
{
  name: 'TokenServiceError',
  message: 'INVALID_TOKEN'
}
// Thrown when the token is malformed and the client is 
// unable to verify with the provider.
{
  name: 'JsonWebTokenError',
  message: 'jwt malformed'
}

ctx.tokenService.refreshToken(String)

/*
 * @async
 * @param {string} token - JWT Token to refresh
 * @return {Promise<string>}
**/
ctx.tokenService.refreshToken(token).then(freshSignedToken => {
  // provide { freshSignedToken } to the client
}).catch(err => {
  // ...error handling
})

ctx.tokenService.revokeToken(String)

/*
 * @async
 * @param {string} subject - subject of JWT Token to deauthorize
 * @return {Promise<string>}
**/
ctx.tokenService.revokeToken(keyId).then(() => {
  // successfully deauthorized the token 
  // across all the clients in audience
}).catch(err => {
  // ...error handling
})

Rejections:

{
  name: 'TokenServiceError',
  message: 'INVALID_KEY_ID'
}

ctx.tokenService.deauthorizeToken(String)

/*
 * @async
 * @param {string} subject - subject of JWT Token to deauthorize
 * @return {Promise<string>}
**/
ctx.tokenService.deauthorizeToken(subject).then(() => {
  // successfully deauthorized the token 
  // across all the clients in audience
}).catch(err => {
  // ...error handling
})

Rejections:

{
  name: 'TokenServiceError',
  message: 'INVALID_SUBJECT'
}

License

Released under the MIT license.

1.0.9

5 years ago

1.0.8

5 years ago

1.0.7

5 years ago

1.0.6

5 years ago

1.0.5

5 years ago

1.0.4

5 years ago

1.0.3

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago