Role of passport.js in Express Application Authentication
- Passport.js implements local authentication strategy. In the example below, passport.js is authenticating using username and password. We have configured the LocalStrategy for username and password authentication that serializes and deserializes the user for session storage.
- We have defined the routed as login, profile, and logout which uses session management for tracking the authenticated users. The Passport.js authenticate middleware is used in the login route to authenticate the user using a local strategy.
- As the /profile route is protected, the application ensures using passport.js that the authenticated users can only access the route. The /logout route is used to change the user logout and redirect to the home page.
Example: Write the following code in the app.js file
Javascript
// app.js const express = require( 'express' ); const pass = require( 'passport' ); const localAuth = require( 'passport-local' ).Strategy; const sess = require( 'express-session' ); const app = express(); // configuring the passport.js middlware pass.use( new localAuth( (username, password, done) => { // demo credentials if (username === 'admin' && password === 'gfg' ) { return done( null , { id: 1, username: 'user' }); } else { return done( null , false , { message: 'Hey Geek! Incorrect username or password.' }); } } )); pass.serializeUser((user, done) => { done( null , user.id); }); pass.deserializeUser((id, done) => { // user retrival const user = { id: 1, username: 'user' }; done( null , user); }); // express middleware app.use(express.urlencoded({ extended: true })); app.use(sess( { secret: 'gfg' , resave: false , saveUninitialized: false })); app.use(pass.initialize()); app.use(pass.session()); // defining routes app.get( '/' , (req, res) => { res.send( '<h1>Passport.js Authentication Example</h1>' ); }); app.get( '/login' , (req, res) => { res.send( '<h1>Login Page</h1><form action="/login" method="post">' + 'Username: <input type="text" name="username"><br>' + 'Password: <input type="password" name="password"><br>' + '<input type="submit" value="Login"></form>' ); }); app.post( '/login' , pass.authenticate( 'local' , { successRedirect: '/profile' , failureRedirect: '/login' , failureFlash: true }) ); app.get( '/profile' , isAuthenticated, (req, res) => { res.send( `<h1>Welcome ${req.user.username}! </h1><a href= "/logout" >Logout</a>` ); }); app.get( '/logout' , (req, res) => { req.logout((err) => { if (err) { return next(err); } res.redirect( '/' ); }); }); // middleware to check if the user is authenticated function isAuthenticated(req, res, next) { if (req.isAuthenticated()) { return next(); } res.redirect( '/login' ); } // starting the server const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server is running on http: //localhost:${PORT}` ); }); |
Step To run the application: Start the server by using the below command.
node app.js
Output:
Explain the use of passport.js for authentication in Express applications.
Authentication is an important aspect of maintaining the overall security of the application. As Express.js is the server-side language, it is important to secure the application with authentication. So we can use Passport.js which is the authentication middleware that has a modular way to implement the authentication strategies which includes the OAuth, username/password, and more authentication features.