Role Based Authentication In HapiJs Using hapi auth jwt2

Posted By : Parveen Kumar Yadav | 27-Jun-2017

In hapiJs we are using JWT token for authentication, but in the doc i didn't found how to actually set role based authentication. So we can achieve this using the

scope keyword

We want to use role based authentication in generally every project so we can achieve this in hapi.js via applying the JwtStrategy. Suppose we want that it first check for userToken authentication and than for role assign for that particular API and if the requesting user have that role tan only it will call the handler or pre function for that API. so for this we can do easily in the auth.js file as follows:-

internals.applyJwtStrategy = function (server, next) {
    const Session = mongoose.model('session');
    const User = mongoose.model('user');

    server.auth.strategy('jwt', 'jwt', {
        key: Config.get('/jwtSecret'),
        verifyOptions: { algorithms: ['HS256'] },

        validateFunc: function (decodedToken, request, callback) {           
                session: function (done) {
                    Session.findByCredentials(decodedToken.sessionId, decodedToken.sessionKey, done);
                user: ['session', function (results, done) {
                    if (!results.session) {
                        return done();

                    User.findById(results.session.user, done);
  }, (err, results) => {
                if (err) {
                    return callback(err);
                if (!results.session) {
                    return callback(null, false);
                results.scope = decodedToken.scope;
                request.pre = results.user
                callback(null, Boolean(results.user), results);


We can pass the requesting user scope from this and need to define scope property in routeOptions object as follow:-

Schema.statics = {
         collectionName: modelName,
         routeOptions: {
             scope: {
                 createScope: "admin"

Now the API only call the handler for this API as if the requesting user role is admin and token is valid. If not then it will return to user as said unauthorised. Hope this would help. Thanks!

Request for Proposal

Recaptcha is required.

Sending message..