Hot to set authentication in passport-jwt with different role of user?
I'm trying to add a role called admin to authenticate admins logged into dashboard web app while the normal user can just access the regular pages.
For a normal user, I require the passport in server.js
like
// use passport
app.use(passport.initialize());
require("./config/passport")(passport);
In the config/passport.js
, like the code in official example, I try this:
const JwtStrategy = require('passport-jwt').Strategy,
ExtractJwt = require('passport-jwt').ExtractJwt;
const mongoose = require('mongoose');
const User = mongoose.model("users");
const key =require("../config/key");
const opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = key.secretKey;
module.exports = passport => {
passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
// console.log(jwt_payload);
User.findById(jwt_payload.id)
.then(user => {
if(user) {
return done(null, user);
}
return done(null, false);
})
.catch(err => console.log(err));
}));
};
This way works fine, and I use them in the route
router.get("/current", passport.authenticate("jwt", {session: false}), (req, res) => {
res.json({
id: req.user.id,
name: req.user.name,
username: req.user.username,
email: req.user.email,
avatar: req.user.avatar,
});
})
However, while I'm adding a role in the token rule:
const rule = {id:admin.id, email: admin.email, avatar: admin.avatar, admin: admin.admin};
How could I check if the admin property is true to query different Collections in passport.js
I tried this, which doesn't work for me with the error seems like the server run twice:
module.exports = passport => {
passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
// console.log(jwt_payload);
if(jwt_payload.admin){
Admin.findById(jwt_payload.id)
.then(user => {
if(user) {
return done(null, user);
}
return done(null, false);
})
.catch(err => console.log(err));
} else {
User.findById(jwt_payload.id)
.then(user => {
if(user) {
return done(null, user);
}
return done(null, false);
})
.catch(err => console.log(err));
}
}));};
The error is :
Error
node.js passport-jwt
add a comment |
I'm trying to add a role called admin to authenticate admins logged into dashboard web app while the normal user can just access the regular pages.
For a normal user, I require the passport in server.js
like
// use passport
app.use(passport.initialize());
require("./config/passport")(passport);
In the config/passport.js
, like the code in official example, I try this:
const JwtStrategy = require('passport-jwt').Strategy,
ExtractJwt = require('passport-jwt').ExtractJwt;
const mongoose = require('mongoose');
const User = mongoose.model("users");
const key =require("../config/key");
const opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = key.secretKey;
module.exports = passport => {
passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
// console.log(jwt_payload);
User.findById(jwt_payload.id)
.then(user => {
if(user) {
return done(null, user);
}
return done(null, false);
})
.catch(err => console.log(err));
}));
};
This way works fine, and I use them in the route
router.get("/current", passport.authenticate("jwt", {session: false}), (req, res) => {
res.json({
id: req.user.id,
name: req.user.name,
username: req.user.username,
email: req.user.email,
avatar: req.user.avatar,
});
})
However, while I'm adding a role in the token rule:
const rule = {id:admin.id, email: admin.email, avatar: admin.avatar, admin: admin.admin};
How could I check if the admin property is true to query different Collections in passport.js
I tried this, which doesn't work for me with the error seems like the server run twice:
module.exports = passport => {
passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
// console.log(jwt_payload);
if(jwt_payload.admin){
Admin.findById(jwt_payload.id)
.then(user => {
if(user) {
return done(null, user);
}
return done(null, false);
})
.catch(err => console.log(err));
} else {
User.findById(jwt_payload.id)
.then(user => {
if(user) {
return done(null, user);
}
return done(null, false);
})
.catch(err => console.log(err));
}
}));};
The error is :
Error
node.js passport-jwt
add a comment |
I'm trying to add a role called admin to authenticate admins logged into dashboard web app while the normal user can just access the regular pages.
For a normal user, I require the passport in server.js
like
// use passport
app.use(passport.initialize());
require("./config/passport")(passport);
In the config/passport.js
, like the code in official example, I try this:
const JwtStrategy = require('passport-jwt').Strategy,
ExtractJwt = require('passport-jwt').ExtractJwt;
const mongoose = require('mongoose');
const User = mongoose.model("users");
const key =require("../config/key");
const opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = key.secretKey;
module.exports = passport => {
passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
// console.log(jwt_payload);
User.findById(jwt_payload.id)
.then(user => {
if(user) {
return done(null, user);
}
return done(null, false);
})
.catch(err => console.log(err));
}));
};
This way works fine, and I use them in the route
router.get("/current", passport.authenticate("jwt", {session: false}), (req, res) => {
res.json({
id: req.user.id,
name: req.user.name,
username: req.user.username,
email: req.user.email,
avatar: req.user.avatar,
});
})
However, while I'm adding a role in the token rule:
const rule = {id:admin.id, email: admin.email, avatar: admin.avatar, admin: admin.admin};
How could I check if the admin property is true to query different Collections in passport.js
I tried this, which doesn't work for me with the error seems like the server run twice:
module.exports = passport => {
passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
// console.log(jwt_payload);
if(jwt_payload.admin){
Admin.findById(jwt_payload.id)
.then(user => {
if(user) {
return done(null, user);
}
return done(null, false);
})
.catch(err => console.log(err));
} else {
User.findById(jwt_payload.id)
.then(user => {
if(user) {
return done(null, user);
}
return done(null, false);
})
.catch(err => console.log(err));
}
}));};
The error is :
Error
node.js passport-jwt
I'm trying to add a role called admin to authenticate admins logged into dashboard web app while the normal user can just access the regular pages.
For a normal user, I require the passport in server.js
like
// use passport
app.use(passport.initialize());
require("./config/passport")(passport);
In the config/passport.js
, like the code in official example, I try this:
const JwtStrategy = require('passport-jwt').Strategy,
ExtractJwt = require('passport-jwt').ExtractJwt;
const mongoose = require('mongoose');
const User = mongoose.model("users");
const key =require("../config/key");
const opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = key.secretKey;
module.exports = passport => {
passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
// console.log(jwt_payload);
User.findById(jwt_payload.id)
.then(user => {
if(user) {
return done(null, user);
}
return done(null, false);
})
.catch(err => console.log(err));
}));
};
This way works fine, and I use them in the route
router.get("/current", passport.authenticate("jwt", {session: false}), (req, res) => {
res.json({
id: req.user.id,
name: req.user.name,
username: req.user.username,
email: req.user.email,
avatar: req.user.avatar,
});
})
However, while I'm adding a role in the token rule:
const rule = {id:admin.id, email: admin.email, avatar: admin.avatar, admin: admin.admin};
How could I check if the admin property is true to query different Collections in passport.js
I tried this, which doesn't work for me with the error seems like the server run twice:
module.exports = passport => {
passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
// console.log(jwt_payload);
if(jwt_payload.admin){
Admin.findById(jwt_payload.id)
.then(user => {
if(user) {
return done(null, user);
}
return done(null, false);
})
.catch(err => console.log(err));
} else {
User.findById(jwt_payload.id)
.then(user => {
if(user) {
return done(null, user);
}
return done(null, false);
})
.catch(err => console.log(err));
}
}));};
The error is :
Error
node.js passport-jwt
node.js passport-jwt
edited Nov 28 '18 at 15:42
Rongkai Liu
asked Nov 28 '18 at 14:58
Rongkai LiuRongkai Liu
32
32
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
Here is what I do and it works pretty well... I simply include the isAdmin: Boolean
in my user model like so:
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 5,
maxlength: 50
},
email: {
type: String,
required: true,
minlength: 5,
maxlength: 255,
unique: true
},
password: {
type: String,
required: true,
minlength: 5,
maxlength: 1024
},
isAdmin: Boolean
});
and then include this in the jwt like so:
userSchema.methods.generateAuthToken = function() {
const token = jwt.sign({ _id: this._id, isAdmin: this.isAdmin }, config.get('jwtPrivateKey'));
return token;
}
then a custom middleware to check the value of isAdmin like so:
module.exports = function (req, res, next) {
if (!req.user.isAdmin) return res.status(403).send('Access denied.');
next();
}
then I simply import it and use it as the second param for any route like so:
router.patch('/:id', [auth, isAdmin, validateObjectId], async (req, res) => {
// handle the route (in order to do anything in this route you would need be an admin...)
});
EDIT: If you're curious about the other two middleware here they are...
auth.js:
const jwt = require('jsonwebtoken');
const config = require('config');
module.exports = function (req, res, next) {
const token = req.header('x-auth-token');
if (!token) return res.status(401).send('Access denied. No token provided.');
try {
const decoded = jwt.verify(token, config.get('jwtPrivateKey'));
req.user = decoded;
next();
}
catch (ex) {
res.status(400).send('Invalid token.');
}
}
validateObjectId:
const mongoose = require('mongoose');
module.exports = function(req, res, next) {
if (!mongoose.Types.ObjectId.isValid(req.params.id))
return res.status(404).send('Invalid ID.');
next();
}
Is that the second param list of middlewares? 'auth' I can change it to normal user authentication and secondly use a customed middleware together?
– Rongkai Liu
Nov 28 '18 at 15:37
the second param is the array[auth, isAdmin, validateObjectId]
... each of the elements in the array are middleware auth is thejwt.verify
middleware,isAdmin
is what I showed you andvalidateObjectId
does exactly what it says... All 3 are middleware that I'm passing as the second argument... if, you're curious I can edit my post to include those two middleware as well...
– SakoBu
Nov 28 '18 at 15:42
Thanks, this way works well!
– Rongkai Liu
Nov 28 '18 at 17:55
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53522307%2fhot-to-set-authentication-in-passport-jwt-with-different-role-of-user%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
Here is what I do and it works pretty well... I simply include the isAdmin: Boolean
in my user model like so:
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 5,
maxlength: 50
},
email: {
type: String,
required: true,
minlength: 5,
maxlength: 255,
unique: true
},
password: {
type: String,
required: true,
minlength: 5,
maxlength: 1024
},
isAdmin: Boolean
});
and then include this in the jwt like so:
userSchema.methods.generateAuthToken = function() {
const token = jwt.sign({ _id: this._id, isAdmin: this.isAdmin }, config.get('jwtPrivateKey'));
return token;
}
then a custom middleware to check the value of isAdmin like so:
module.exports = function (req, res, next) {
if (!req.user.isAdmin) return res.status(403).send('Access denied.');
next();
}
then I simply import it and use it as the second param for any route like so:
router.patch('/:id', [auth, isAdmin, validateObjectId], async (req, res) => {
// handle the route (in order to do anything in this route you would need be an admin...)
});
EDIT: If you're curious about the other two middleware here they are...
auth.js:
const jwt = require('jsonwebtoken');
const config = require('config');
module.exports = function (req, res, next) {
const token = req.header('x-auth-token');
if (!token) return res.status(401).send('Access denied. No token provided.');
try {
const decoded = jwt.verify(token, config.get('jwtPrivateKey'));
req.user = decoded;
next();
}
catch (ex) {
res.status(400).send('Invalid token.');
}
}
validateObjectId:
const mongoose = require('mongoose');
module.exports = function(req, res, next) {
if (!mongoose.Types.ObjectId.isValid(req.params.id))
return res.status(404).send('Invalid ID.');
next();
}
Is that the second param list of middlewares? 'auth' I can change it to normal user authentication and secondly use a customed middleware together?
– Rongkai Liu
Nov 28 '18 at 15:37
the second param is the array[auth, isAdmin, validateObjectId]
... each of the elements in the array are middleware auth is thejwt.verify
middleware,isAdmin
is what I showed you andvalidateObjectId
does exactly what it says... All 3 are middleware that I'm passing as the second argument... if, you're curious I can edit my post to include those two middleware as well...
– SakoBu
Nov 28 '18 at 15:42
Thanks, this way works well!
– Rongkai Liu
Nov 28 '18 at 17:55
add a comment |
Here is what I do and it works pretty well... I simply include the isAdmin: Boolean
in my user model like so:
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 5,
maxlength: 50
},
email: {
type: String,
required: true,
minlength: 5,
maxlength: 255,
unique: true
},
password: {
type: String,
required: true,
minlength: 5,
maxlength: 1024
},
isAdmin: Boolean
});
and then include this in the jwt like so:
userSchema.methods.generateAuthToken = function() {
const token = jwt.sign({ _id: this._id, isAdmin: this.isAdmin }, config.get('jwtPrivateKey'));
return token;
}
then a custom middleware to check the value of isAdmin like so:
module.exports = function (req, res, next) {
if (!req.user.isAdmin) return res.status(403).send('Access denied.');
next();
}
then I simply import it and use it as the second param for any route like so:
router.patch('/:id', [auth, isAdmin, validateObjectId], async (req, res) => {
// handle the route (in order to do anything in this route you would need be an admin...)
});
EDIT: If you're curious about the other two middleware here they are...
auth.js:
const jwt = require('jsonwebtoken');
const config = require('config');
module.exports = function (req, res, next) {
const token = req.header('x-auth-token');
if (!token) return res.status(401).send('Access denied. No token provided.');
try {
const decoded = jwt.verify(token, config.get('jwtPrivateKey'));
req.user = decoded;
next();
}
catch (ex) {
res.status(400).send('Invalid token.');
}
}
validateObjectId:
const mongoose = require('mongoose');
module.exports = function(req, res, next) {
if (!mongoose.Types.ObjectId.isValid(req.params.id))
return res.status(404).send('Invalid ID.');
next();
}
Is that the second param list of middlewares? 'auth' I can change it to normal user authentication and secondly use a customed middleware together?
– Rongkai Liu
Nov 28 '18 at 15:37
the second param is the array[auth, isAdmin, validateObjectId]
... each of the elements in the array are middleware auth is thejwt.verify
middleware,isAdmin
is what I showed you andvalidateObjectId
does exactly what it says... All 3 are middleware that I'm passing as the second argument... if, you're curious I can edit my post to include those two middleware as well...
– SakoBu
Nov 28 '18 at 15:42
Thanks, this way works well!
– Rongkai Liu
Nov 28 '18 at 17:55
add a comment |
Here is what I do and it works pretty well... I simply include the isAdmin: Boolean
in my user model like so:
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 5,
maxlength: 50
},
email: {
type: String,
required: true,
minlength: 5,
maxlength: 255,
unique: true
},
password: {
type: String,
required: true,
minlength: 5,
maxlength: 1024
},
isAdmin: Boolean
});
and then include this in the jwt like so:
userSchema.methods.generateAuthToken = function() {
const token = jwt.sign({ _id: this._id, isAdmin: this.isAdmin }, config.get('jwtPrivateKey'));
return token;
}
then a custom middleware to check the value of isAdmin like so:
module.exports = function (req, res, next) {
if (!req.user.isAdmin) return res.status(403).send('Access denied.');
next();
}
then I simply import it and use it as the second param for any route like so:
router.patch('/:id', [auth, isAdmin, validateObjectId], async (req, res) => {
// handle the route (in order to do anything in this route you would need be an admin...)
});
EDIT: If you're curious about the other two middleware here they are...
auth.js:
const jwt = require('jsonwebtoken');
const config = require('config');
module.exports = function (req, res, next) {
const token = req.header('x-auth-token');
if (!token) return res.status(401).send('Access denied. No token provided.');
try {
const decoded = jwt.verify(token, config.get('jwtPrivateKey'));
req.user = decoded;
next();
}
catch (ex) {
res.status(400).send('Invalid token.');
}
}
validateObjectId:
const mongoose = require('mongoose');
module.exports = function(req, res, next) {
if (!mongoose.Types.ObjectId.isValid(req.params.id))
return res.status(404).send('Invalid ID.');
next();
}
Here is what I do and it works pretty well... I simply include the isAdmin: Boolean
in my user model like so:
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 5,
maxlength: 50
},
email: {
type: String,
required: true,
minlength: 5,
maxlength: 255,
unique: true
},
password: {
type: String,
required: true,
minlength: 5,
maxlength: 1024
},
isAdmin: Boolean
});
and then include this in the jwt like so:
userSchema.methods.generateAuthToken = function() {
const token = jwt.sign({ _id: this._id, isAdmin: this.isAdmin }, config.get('jwtPrivateKey'));
return token;
}
then a custom middleware to check the value of isAdmin like so:
module.exports = function (req, res, next) {
if (!req.user.isAdmin) return res.status(403).send('Access denied.');
next();
}
then I simply import it and use it as the second param for any route like so:
router.patch('/:id', [auth, isAdmin, validateObjectId], async (req, res) => {
// handle the route (in order to do anything in this route you would need be an admin...)
});
EDIT: If you're curious about the other two middleware here they are...
auth.js:
const jwt = require('jsonwebtoken');
const config = require('config');
module.exports = function (req, res, next) {
const token = req.header('x-auth-token');
if (!token) return res.status(401).send('Access denied. No token provided.');
try {
const decoded = jwt.verify(token, config.get('jwtPrivateKey'));
req.user = decoded;
next();
}
catch (ex) {
res.status(400).send('Invalid token.');
}
}
validateObjectId:
const mongoose = require('mongoose');
module.exports = function(req, res, next) {
if (!mongoose.Types.ObjectId.isValid(req.params.id))
return res.status(404).send('Invalid ID.');
next();
}
edited Nov 28 '18 at 15:53
answered Nov 28 '18 at 15:23
SakoBuSakoBu
1,761521
1,761521
Is that the second param list of middlewares? 'auth' I can change it to normal user authentication and secondly use a customed middleware together?
– Rongkai Liu
Nov 28 '18 at 15:37
the second param is the array[auth, isAdmin, validateObjectId]
... each of the elements in the array are middleware auth is thejwt.verify
middleware,isAdmin
is what I showed you andvalidateObjectId
does exactly what it says... All 3 are middleware that I'm passing as the second argument... if, you're curious I can edit my post to include those two middleware as well...
– SakoBu
Nov 28 '18 at 15:42
Thanks, this way works well!
– Rongkai Liu
Nov 28 '18 at 17:55
add a comment |
Is that the second param list of middlewares? 'auth' I can change it to normal user authentication and secondly use a customed middleware together?
– Rongkai Liu
Nov 28 '18 at 15:37
the second param is the array[auth, isAdmin, validateObjectId]
... each of the elements in the array are middleware auth is thejwt.verify
middleware,isAdmin
is what I showed you andvalidateObjectId
does exactly what it says... All 3 are middleware that I'm passing as the second argument... if, you're curious I can edit my post to include those two middleware as well...
– SakoBu
Nov 28 '18 at 15:42
Thanks, this way works well!
– Rongkai Liu
Nov 28 '18 at 17:55
Is that the second param list of middlewares? 'auth' I can change it to normal user authentication and secondly use a customed middleware together?
– Rongkai Liu
Nov 28 '18 at 15:37
Is that the second param list of middlewares? 'auth' I can change it to normal user authentication and secondly use a customed middleware together?
– Rongkai Liu
Nov 28 '18 at 15:37
the second param is the array
[auth, isAdmin, validateObjectId]
... each of the elements in the array are middleware auth is the jwt.verify
middleware, isAdmin
is what I showed you and validateObjectId
does exactly what it says... All 3 are middleware that I'm passing as the second argument... if, you're curious I can edit my post to include those two middleware as well...– SakoBu
Nov 28 '18 at 15:42
the second param is the array
[auth, isAdmin, validateObjectId]
... each of the elements in the array are middleware auth is the jwt.verify
middleware, isAdmin
is what I showed you and validateObjectId
does exactly what it says... All 3 are middleware that I'm passing as the second argument... if, you're curious I can edit my post to include those two middleware as well...– SakoBu
Nov 28 '18 at 15:42
Thanks, this way works well!
– Rongkai Liu
Nov 28 '18 at 17:55
Thanks, this way works well!
– Rongkai Liu
Nov 28 '18 at 17:55
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53522307%2fhot-to-set-authentication-in-passport-jwt-with-different-role-of-user%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown