Skip to content

Multiple strategies with one scheme - 'hapi-auth-jwt2' in Hapi.js #73

@heron2014

Description

@heron2014

wip

If you want to register two different strategies depends on the routes, based on hapi-auth-jwt2scheme, follow these steps:

  • using plugins:
    Create your plugins for 'some-strategy':
'use strict';

exports.register = function (server, options, next) {

  server.auth.strategy('some-name', 'jwt', false,
  {
    key: process.env.JWT_SECRET_CLIENT,
    validateFunc: customValidate,
    verifyOptions: { ignoreExpiration: true }, cookieKey: 'name-of-your-token'
  });

  return next();
}

exports.register.attributes = {
  name: 'SomeAuthentication'
};

On your handler create/save token and pass it in a cookie

....
//check your password, compare, create session and store in db, create token as JWT 
...

return redirect('/dashboard').state('name-of-your-token', token);

other plugin for different strategy

var validate = require('./validate');

exports.register = function (server, options, next) {

  server.auth.strategy('jwt', 'jwt', false,
  { key: process.env.JWT_SECRET,
    validateFunc: validate,
    verifyOptions: { ignoreExpiration: true }
  });

  return next();
}

exports.register.attributes = {
  name: 'Authentication'
};

In a handler:

On your handler create/save token and pass it in a cookie for example. 
```js

....
//check your password, compare, create session and store in db, create token as JWT 
...

return redirect('/dashboard').state('token', token);

We dont need to specify cookieKey in above because as default is looking for 'token' - check L10

-register these plugins it to your server/index
-defined your customValidate function

We had an issue of not calling the validate function on one of the strategies (on some routes). Our token on that route was undefined. We resolved it by passing cookieKey with the correct name of the token.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions