• Stars
    star
    169
  • Rank 219,952 (Top 5 %)
  • Language
    JavaScript
  • License
    Other
  • Created over 10 years ago
  • Updated over 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

JSON Web Token (JWT) authentication plugin

hapi-auth-jwt

hapi JSON Web Token (JWT) authentication plugin

Build Status

JSON Web Token authentication requires verifying a signed token. The 'jwt' scheme takes the following options:

  • key - (required) The private key the token was signed with.
  • validateFunc - (optional) validation and user lookup function with the signature function(request, token, callback) where:
    • request - is the hapi request object of the request which is being authenticated.
    • token - the verified and decoded jwt token
    • callback - a callback function with the signature function(err, isValid, credentials) where:
      • err - an internal error.
      • isValid - true if the token was valid otherwise false.
      • credentials - a credentials object passed back to the application in request.auth.credentials. Typically, credentials are only included when isValid is true, but there are cases when the application needs to know who tried to authenticate even when it fails (e.g. with authentication mode 'try').
  • verifyOptions - settings to define how tokens are verified by the jsonwebtoken library
    • 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
    • issuer: if you want to check issuer (iss), provide a value here
    • ignoreExpiration: if true do not validate the expiration of the token.
    • maxAge: optional sets an expiration based on the iat field. Eg 2h

See the example folder for an executable example.

var Hapi = require('hapi'),
    jwt = require('jsonwebtoken'),
    server = new Hapi.Server();

server.connection({ port: 8080 });


var accounts = {
    123: {
        id: 123,
        user: 'john',
        fullName: 'John Doe',
        scope: ['a', 'b']
    }
};


var privateKey = 'BbZJjyoXAdr8BUZuiKKARWimKfrSmQ6fv8kZ7OFfc';

// Use this token to build your request with the 'Authorization' header.  
// Ex:
//     Authorization: Bearer <token>
var token = jwt.sign({ accountId: 123 }, privateKey, { algorithm: 'HS256'} );


var validate = function (request, decodedToken, callback) {

    var error,
        credentials = accounts[decodedToken.accountId] || {};

    if (!credentials) {
        return callback(error, false, credentials);
    }

    return callback(error, true, credentials)
};


server.register(require('hapi-auth-jwt'), function (error) {

    server.auth.strategy('token', 'jwt', {
        key: privateKey,
        validateFunc: validate,
        verifyOptions: { algorithms: [ 'HS256' ] }  // only allow HS256 algorithm
    });

    server.route({
        method: 'GET',
        path: '/',
        config: {
            auth: 'token'
        }
    });

    // With scope requirements
    server.route({
        method: 'GET',
        path: '/withScope',
        config: {
            auth: {
                strategy: 'token',
                scope: ['a']
            }
        }
    });
});


server.start();

More Repositories

1

vogels

DynamoDB data mapper for node.js
JavaScript
698
star
2

node-circuitbreaker

circuit breaker is used to provide stability and prevent cascading failures in distributed systems
JavaScript
48
star
3

pergola

pergola is a web frontend to mongoDB based on padrino and jquery
JavaScript
12
star
4

hapi-seed

seed project for a client side angular.js app calling a REST api built with hapi
12
star
5

cloudformation-elasticsearch

aws cloudformation and puppet scripts to deploy elasticsearch on aws
Puppet
8
star
6

mongobacker

command line tool to backup and restore mongodb instances with s3
Ruby
6
star
7

AsyncDisplayKitHeaderNodeExample

example swift app showing how to render ASDisplayNode's as table view headers
Swift
6
star
8

RFSectionDelta

Calculate deltas between arrays for applying batch updates to UITableView's and UICollectionView's
Swift
6
star
9

elasticauth-api

Hapi plugin providing a complete auth solution for running on AWS
JavaScript
6
star
10

vogels-lambda

example project using vogels with AWS lambda
JavaScript
3
star
11

grunt-init-hapi

Grunt scaffolding for a hapi based web service
JavaScript
2
star
12

dotfiles

my configs for bash, git, ruby...
Emacs Lisp
2
star
13

hapi-rate-limit-proxy

hapi rate limiter proxy plugin
JavaScript
1
star
14

playbooks

ansible playbooks
Shell
1
star
15

sleeping-giant

REST api for mongoDB
Ruby
1
star
16

node-boltbus

distributed eventemitter powered by AWS
JavaScript
1
star
17

workstation

puppet modules for an Ubuntu workstation
Puppet
1
star
18

erlang_programming_book

example exercises from the erlang programming book
1
star
19

node-cowork

distributed job queue backed by AWS
JavaScript
1
star
20

onboarding

example ios onboarding screens written completely in swift
Swift
1
star