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) {
Async.auto({
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!
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Parveen Kumar Yadav
Parveen is an experienced Java Developer working on Java, J2EE, Spring, Hibernate, Grails ,Node.js,Meteor,Blaze, Neo4j, MongoDB, Wowza Streaming Server,FFMPEG,Video transcoding,Amazon web services, AngularJs, javascript. He likes to learn new technologies