Disabling Sessions in Passport.js
Last Updated :
22 Nov, 2022
In a common web application, the credentials used to authenticate a user will only be transmitted during the login request. Passport will establish a persistent login session after successful authentication. This session is maintained via a cookie in the user’s browser.
However, in some cases, session support is not required. For instance, API servers supply require credentials with each request to be authenticated. In this scenario, you can disable session support. You, need to set the session option to false.
app.post('/auth',
passport.authenticate('local-signin', {
successRedirect : '/dashboard',
failureRedirect : '/login',
session: false
})
)
Alternatively, a custom callback can be provided to allow the application to handle success or failure.
app.get('/auth', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
// your logic to how you serve your user
})(req, res, next);
});
In the above example, the passport.authenticate() is called from within the route handler, rather than being used as route middleware. This gives the callback access to the req and res objects and the next method through closure.
Example: In a typical web application the user will redirect to the login page after register. So, here we don’t need to create a session after the new registration. Let’s see the implementation.
Project Setup: Create a new NodeJS project and name it Auth.
mkdir Auth && cd Auth
npm init -y
Install Dependencies:
Project Structure: It will look like this.
- passport-config.js: This is the passport configuration file.
- register.ejs: This is the view of the register page.
- index.js: This main server setup file.
register.ejs
<html lang= "en" >
<head>
<meta charset= "UTF-8" >
<meta http-equiv= "X-UA-Compatible" content= "IE=edge" >
<meta name= "viewport" content= "width=device-width, initial-scale=1.0" >
<title>Document</title>
<style>
.container{
position: relative;
width: 400px;
padding: 8px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
box-shadow: black 0 0 14px 8px;
}
label{
font-size: 17px;
display: block;
}
input{
display: block;
margin: 4px;
padding: 4px 8px;
height: 31px;
width: 350px;
font-size: 22px;
}
.btn-submit{
border-radius: 2px;
padding: 10px 17px;
background-color: green;
border: none;
color: white;
font-weight: bold;
cursor: pointer;
width: 120px;
height: 44px;
}
.btn-submit:hover{
opacity: 0.8;
}
.brand{
text-align: center;
color: #c2bfbf;
}
</style>
</head>
<body>
<div class= "container" >
<h1 class= "brand" >GeeksForGeeks</h1>
<h2>Register</h2>
<form action= "/register" method= "POST" >
<label for = "email" >Email: </label>
<input id= "userEmail" name= "email" type= "email" >
<label for = "password" >Password: </label>
<input id= "userPassword" name= "password" type= "password" >
<input class= "btn-submit" type= "submit" value= "Register" >
</form>
</div>
</body>
</html>
|
passport-config.js
const LocalStrategy = require( 'passport-local' ).Strategy
const bcrypt = require( 'bcrypt' )
const { v4: uuid } = require( 'uuid' )
const initialize = (passport, getUserByEmail, save) => {
const register = async (email, password, done) => {
const user = getUserByEmail(email)
if (user != null )
return done( null , user, {
message: "You are already registered" })
const hashedPassword = await bcrypt.hash(password, 10)
const newUser = {
id: uuid(),
email: email,
password: hashedPassword
}
save(newUser)
return done( null , newUser, {
message: "Registration Successful" })
}
passport.use('local-signup ', new LocalStrategy({
usernameField: ' email ',
passwordField: ' password'
}, register))
}
module.exports = initialize
|
index.js
const express = require( 'express' )
const bodyParser = require( 'body-parser' )
const passport = require( 'passport' )
const ejs = require( 'ejs' )
const intializePassport = require( './config/passport-config' )
const app = express()
const port = 8080
const Users = []
app.use( bodyParser.urlencoded( { extended: false } ) )
intializePassport(
passport,
email => Users.find(user => user.email === email),
user => Users.push(user)
)
app.set( 'view engine' , 'ejs' )
app.get( '/' , (req, res)=> res.render( 'register.ejs' ))
app.post( '/register' , (req, res, next)=> {
passport.authenticate( 'local-signup' ,
(err, user, info)=>{
if (err)
res
.status(500)
.send( "<H1> Server Error! </H1>" )
else {
console.log({
Error: err,
User: user,
Message: info.message
})
res.send(`<H1> ${ info.message } <H1>`)
}
})(req, res, next)
})
app.listen(port, () => console.log(`Server listening on port ${port}!`))
|
Step to run application: Run the index.js file using the following command:
node index.js
Output: We will see the following output on the terminal screen.
Server listening on port 8080
Now open any browser and go to http://localhost:8080/, we will see the following output:
Registration Form
After submitting the form, we will see the Registration Successful on the browser and also see the following output on the terminal screen:
Server Terminal
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...