'What's the difference between req.isAuthenticated() and passport.authenticate() in passport?
I am a beginner in programmation and experimenting the authentication process through node.js, express and mongoDB. I have used passport, passport-local and passport-local-mongoose to create a login/logout for users.
When my authentication succeed, user is redirect to my index page which show his/her name.
But I have a question… What is the difference between req.isAuthenticated() and passport.authenticate() ?
In my main.js, I have directly placed my req.user in the core of my session :
const passport = require('passport');
const expressSession =require('express-session');
const cookieParser = require('cookie-parser');
const connectFlash = require('connect-flash')
const localStrategy = require('passport-local').Strategy;
app.use(cookieParser("SecretStringForCookies"));
app.use(
expressSession({
secret : "SecretStringForCookies",
cookie : {
maxAge: 2000000
},
resave : false,
saveUninitialized : false
}))
app.use(passport.initialize());
app.use(passport.session());
//Serializing and deserializing user for checking login status in cookie
const User = require('./models/allUsers');
passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use(connectFlash());
app.use((req, res, next) => {
res.locals.flashMessages = req.flash();
res.locals.currentUser = req.user;
next();
});
For my authentication to succeed, I have used the following code in a UserController.js page :
module.exports = {
authentication : passport.authenticate("local", {
failureRedirect: "/login",
successRedirect: "/index",
successFlash : { type: 'success_msg', message: 'Welcome !' },
failureFlash : { type: 'error_msg', message: 'Your email and/or password are wrong, try again !' }
}),
isAuthenticatedUser : (req, res, next) => {
if(req.isAuthenticated()) {
next();
}
res.redirect = "/login";
},
}
My routes regarding the authentification :
const express = require('express');
const router = express.Router();
const userController = require('./userController');
router.post('/login', userController.authenticate, userController.isAuthenticatedUser);
router.get("/logout", userController.isAuthenticatedUser, (req, res)=> {req.logout(), res.redirect("/")});
router.get('/index');
My HTML :
<nav class="nav-links">
<% if(currentUser) { %>
<ul>
<li><%= currentUser.name %></li>
<li><a href="/logout">Logout</a></li>
<li><a href="/index">Home</a></li>
</ul>
<% } %>
</nav>
However, my login authentication process seems to work fine with just only passport.authenticate() and my routes for login/logout doesn’t seem to need my function about req.isAuthenticated().
Sorry if my question seems dumb or weird but I am really confused about its purpose…
Could you please give me some advice ?
Thank you in advance for your help !
Solution 1:[1]
The req.isAuthenticated() command returns whether the user is logged in or not, and the other ensures that the user is logged in.
Solution 2:[2]
passport.authenticate()
method extracts user credentials from request
object and passes them to the authentication function which you use to authenticate the process,
passport.use(new LocalStrategy(
function(username, password, done) { // this is an authentication function
User.findOne({ username: username }, function (err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false); }
if (!user.verifyPassword(password)) { return done(null, false); }
return done(null, user);
});
}
));
By default, when authentication succeeds, the req.user
property is set to the authenticated user, a session is established, and the next function in the stack is called.
req.isAuthenticated()
method checks if the user is already authenticated by the authentication function or not, for example, if you have an admin dashboard page and you want to ensure that only authenticated users can access this page, therefore you use req.isAuthenticated()
method to ensure that the user who sends the request is already authenticated by the authentication function.
module.exports= (req,res, next)=>{
if(req.isAuthenticated()){ //checks whether user
//is authenticated by the passport.authenticate() method
next();
}
res.redirect('/login');
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ahmet U?ur |
Solution 2 | Abdurrahim Ahmadov |