My frontend is in React and backend is Node/Express. I am using 2 types of Passport strategies:
- JWT
Some users log in with email/password and are authenticated by passport.Authenticate('jwt', {session:false})
while some users are authenticated by passport.Authenticate('google')
. Both type of uses get authenticated successfully (independently).
The issue is the JWT users send a bearer token and Google users are automatic through session cookies.
So, if I create a route like:
app.get('/profile', passport.authenticate('jwt',{session:false}), showProfile)
this will authenticate only the JWT users and fail the Google users. If I change it to:
app.get('/profile', passport.authenticate('google'), showProfile)
this will authenticate only the Google users.
I want a generic code to authenticate both types of users. So if I create a middleware like:
function isLoggedIn(req, res, next){
// bearer token exists
//execute passport authentication for jwt
}else{
//check if req.user exists
//if yes call next()
}
Is there a way to switch between the two middleware calls? How to make both JWT and Google validations. I have no issues with Google login and stuff, just the application's protected routes.
CodePudding user response:
I found the solution finally.
const verifyToken = (req, res, next) => {
// console.log(req.headers)
const bearerHeader = req.headers['authorization']
console.log({bearerHeader})
if (bearerHeader){
const bearer = bearerHeader.split(' ')
req.token = bearer[1]
next()
}else{
next()
}
}
const isLoggedIn = (req, res, next)=> {
if (req.user){
console.log('OAuth User was found')
next()
}else {
if (req.token) {
console.log('Bearer token was found')
// user is a jwt user
passport.authenticate('jwt', {session:false})(req, res, next)
// next()
}else{
res.sendStatus(401)
}
}
}
userController.get('/userList', verifyToken, isLoggedIn,(req, res) => {
User.find({}, (err, result) => res.status(200).json({data: result}))
}
)
Yes, there is a lot of scope of refinement, which I will do in due course.
CodePudding user response:
I though you re asking about only one custom middleware, how about test to make into one ? if it doesn't work unfortunately i will remove my answer.
function isLoggedIn (req, res, next) {
if (req.user) { // or req.isAuthenticated() ?
console.log('OAuth User was found')
next();
} else if (req.headers.authorization) {
passport.authenticate('jwt', {session: false})
(req, res, next);
} else {
res.status(401).json({error: "ACCESS DENIED"})
}
};
userController.get('/userList', isLoggedIn, (req, res) => {
User.find({}, (err, result) => res.status(200).json({data: result}))
});