All Projects → now-ims → hapi-now-auth

now-ims / hapi-now-auth

Licence: MIT license
Hapi token auth for bearer and jwt

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to hapi-now-auth

hapi-plugin-mysql
Hapi plugin for MySQL
Stars: ✭ 17 (-60.47%)
Mutual labels:  hapi, hapijs, hapi-plugin
hapi-good-winston
A good reporter to send and log events with winston
Stars: ✭ 21 (-51.16%)
Mutual labels:  hapi, hapijs, hapi-plugin
hapi-routes
Hapi plugin for registering routes
Stars: ✭ 12 (-72.09%)
Mutual labels:  hapijs, hapi-plugin
hapi-moon
Hassle-free and production ready hapi.js Server boilerplate
Stars: ✭ 23 (-46.51%)
Mutual labels:  hapi, hapijs
nodejs-tutorials-hapi
Examples for the hapi tutorial series within the Future Studio University
Stars: ✭ 70 (+62.79%)
Mutual labels:  hapi, hapijs
hapi-cli
CLI to build API with Hapi, mongodb and mongoose. Work with Hapi V17.
Stars: ✭ 36 (-16.28%)
Mutual labels:  hapi, hapijs
typesafe-hapi
Typechecking for HapiJS based on Joi schemas!
Stars: ✭ 21 (-51.16%)
Mutual labels:  hapi, hapijs
hapi-statsd
A hapi plugin for sending request round trip metrics to statsd
Stars: ✭ 29 (-32.56%)
Mutual labels:  hapi, hapi-plugin
hapi-sequelizejs
A hapi.js plugin to connect with Sequelize ORM
Stars: ✭ 56 (+30.23%)
Mutual labels:  hapi, hapi-plugin
hapi-dev-errors
A hapi plugin to return better error details and skip the look at command line to catch the issue.
Stars: ✭ 58 (+34.88%)
Mutual labels:  hapi, hapi-plugin
sapper-authentication-demo
A demonstration of Auth with Sapper + JWT + Server Side Rendering + RBAC
Stars: ✭ 102 (+137.21%)
Mutual labels:  hapi, hapijs
hapi-mongo-models
📦 A hapi plugin for `mongo-models`
Stars: ✭ 101 (+134.88%)
Mutual labels:  hapi, hapi-plugin
hapi-sentry
A hapi plugin for request error logging to Sentry
Stars: ✭ 24 (-44.19%)
Mutual labels:  hapi, hapi-plugin
Crashlyzer
Crash viewer web application for displaying the crashes reported by rn-crash-reporter components from React Native mobile applications.
Stars: ✭ 59 (+37.21%)
Mutual labels:  hapi, hapijs
hapi-docs
Beautiful API documentation generator for Hapi using Vue
Stars: ✭ 64 (+48.84%)
Mutual labels:  hapi, hapi-plugin
good-sentry
Sentry broadcasting for good process monitor
Stars: ✭ 15 (-65.12%)
Mutual labels:  hapi, hapijs
Hapi
The Simple, Secure Framework Developers Trust
Stars: ✭ 13,632 (+31602.33%)
Mutual labels:  hapi
kubernetes-starterkit
A launchpad for developers to learn Kubernetes from scratch and deployment of microservices on a kubernetes cluster.
Stars: ✭ 39 (-9.3%)
Mutual labels:  hapijs
Hapi Openapi
Build design-driven apis with OpenAPI (formerly swagger) 2.0 and hapi.
Stars: ✭ 196 (+355.81%)
Mutual labels:  hapi
Hapijs.com
The hapijs.com website
Stars: ✭ 181 (+320.93%)
Mutual labels:  hapi

hapi authentication plugin

Hapi Now Auth Test Runner

Note: this plugin is for hapi v17+

This authentication package was inspired by hapi-auth-bearer-token and hapi-auth-jwt2

hapi-now-auth takes care of verifying your JWTs or bearer tokens. We will try to provide the best documentation possible, but reachout should you need help.

Install

You can add the plugin to you project using npm or yarn:
npm:npm i @now-ims/hapi-now-auth
yarn:yarn add @now-ims/hapi-now-auth

Hapi Now Auth Scheme

This plugin creates a hapi-now-auth authentication scheme with the following options:

  • validate - (required) your validation function with [async] function(request, token, h) where:
    • request is the hapi request object
    • token
      • if (verifyJWT === false)
        • the auth token received from the client
      • if (verifyJWT === true)
        • object { decodedJWT, token }
    • h the hapi response toolkit
    • Response
      • { isValid, credentials, artifacts } where:
        • isValid true if JWT or Bearer token is valid
        • credentials an object passed back to your application in request.auth.credentials
        • artifacts optional related data
  • options (Optional)
    • accessTokenName - (Default: 'authorization', Type: string)
    • allowQueryToken - (Default: false, Type: boolean)
    • allowCookieToken - (Default: false, Type: boolean)
    • allowMultipleHeaders - (Default: false, Type: boolean) - accept multiple headers, e.g., Authorization Bearer <token>; Authorization JWT <token>
    • tokenType - (Default: Bearer, Type: string) - accept a custom token type e.g., Authorization JWT <token>
    • allowChaining - (Default: false, Type: boolean) - permit additional authentication strategies
    • unauthorized - (Default: Boom.unauthorized, Type: function) - e.g., function(message, scheme, attributes)
    • verifyJWT - (Default: false, Type: boolean) - verify and decode JWT (note: validate function will need to accept object of { decodedJWT, token })
    • keychain - (Required if verifyJWT: True, Type: array[string]) - an array of your secret keys
    • verifyOptions - (Optional, Type: object)
      • algorithms - (*Default: ['HS256'], Type: array)
      • audience - (Optional, Type: array) - if you want to check the audience aud supply an array to be checked
      • issuer - (Optional, Type: array) - array of strings of valid values for iss field
      • ignoreExpiration - (Default: false, Type: boolean) - ignore exp
      • ignoreNotBefore - (Default: false, Type: boolean) - ignore nbf
      • subject - (Optional, Type: string)
      • clockTolerance - (Optional, Type: integer) - number of seconds to tolerate when checking nbf or exp claims. note: assists with minor clock differences
      • maxAge - (Optional, Type: string) - maximum allowed age for tokens to still be valid - e.g., 2 days, 1 hour, 15m
      • clockTimestamp - the time in seconds that should be used as current time for all necessary comparisons

Working example

const Hapi = require('hapi');
const HapiNowAuth = require('@now-ims/hapi-now-auth');

// create your hapi server
const server = Hapi.server({ port: 8000 });

// Start server function
async function start() {
  // register hapi-now-auth plugin
  try {
    await server.register(HapiNowAuth);
  } catch (error) {
    console.error(error);
    process.exit(1);
  }

  server.auth.strategy('jwt-strategy', 'hapi-now-auth', {
    verifyJWT: true,
    keychain: [process.env.SECRET_KEY],
    validate: async (request, token, h) => {
      let isValid, artifacts;

      /**
       * we asked the plugin to verify the JWT
       * we will get back the decodedJWT as token.decodedJWT
       * and we will get the JWT as token.token
       */

      const credentials = token.decodedJWT;

      /**
       * return the decodedJWT to take advantage of hapi's
       * route authentication options
       * https://hapijs.com/api#authentication-options
       */

      /**
       * Validate your token here
       * For example, compare to your redis store
       */

      redis.get(token, (error, result) => {
        if (error) {
          isValid = false;
          artifacts.error = error;
          return { isValid, credentials, artifacts };
        }
        isValid = true;
        artifacts.info = result;
        return { isValid, credentials, artifacts };
      });
    },
  });

  server.auth.default('jwt-strategy');

  server.route({
    method: 'GET',
    path: '/',
    handler: async (request, h) => {
      return { info: 'success!' };
    },
    options: {
      auth: false,
    },
  });

  server.route({
    method: 'GET',
    path: '/protected',
    handler: async (request, h) => {
      return { info: 'success if JWT is verified!' };
    },
  });

  server.route({
    method: 'GET',
    path: '/admin',
    handler: async (request, h) => {
      return { info: 'success if JWT is verified and scope includes admin' };
    },
    options: {
      auth: {
        scope: 'admin',
      },
    },
  });

  try {
    await server.start();
  } catch (error) {
    console.error(error);
    process.exit(1);
  }

  console.log(`Server running at: ${server.info.uri}`);
}

// Don't worry be hapi
start();

Acknowledgement

This project is kindly sponsored by Now IMS

Licensed under MIT

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].