TEN
TEN

Reputation: 91

Multiple passport-jwt strategy in the same app

How can I created two different passport-jwt using different passwords and use it to authenticate two different roles?

Example:

var passport_admin = require('../../node_modules/passport'); 
var passport_user = require('../../node_modules/passport'); 

require('../auth_layer/admin_jwt_auth')(passport_admin); 
require('../auth_layer/user_jwt_auth')(passport_user); 

app.post('/admin/profile',passport_admin.authenticate('jwt',{session:false}), business_admin.post_profile);

app.post('/user/profile',passport_user.authenticate('jwt',{session:false}), business_admin.post_profile);

When I do the above it does not work(401 when verifying token) because I require two different authentication midleware in my route.

How can I achieve that? or Does it make sense to do it?

Thanks for your help.

Upvotes: 6

Views: 7563

Answers (2)

mc.
mc.

Reputation: 549

This solution allows you to use the same url for both strategies, just name them.

https://github.com/mikenicholson/passport-jwt/issues/182

Upvotes: 0

dtm7
dtm7

Reputation: 361

I had exactly the same issue with you but after a number of research, trials and errors, I found my own method in solving this problem and wanted to share it with you. First on your syntax below, only one rule will be implemented:

    var passport_admin = require('../../node_modules/passport'); 
    var passport_user = require('../../node_modules/passport'); 

The rule which will be used is only the latest which is passport_user. To tackle this, you need to go to your passport.js api and create two passport rules with different names (in the same js file) like below

    passport.use('admin-rule',
    new JwtStrategy(opts, (...........) => {.........
    }));

    passport.use('user-rule',
    new JwtStrategy(opts, (...........) => {.........
    }));

Then you want to use the 'admin-rule' on your admin syntax, same idea with user syntax (use 'user-rule').

    app.post('/admin/profile',passport_admin.authenticate('admin-rule'
    {session:false}), business_admin.post_profile);

That way your admin & user will use the specified passport rule on it's router.

Upvotes: 25

Related Questions