Express sessions and using passport for Authentication

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 305:- Express sessions and using passport for Authentication

In this section, we will learn how to use Passport.js for authentication in our Express.js web application.

Before we start with Passport.js, let's first discuss the concept of sessions in Express.js.

Express Sessions

A session is a place to store data that you want to persist across requests. Sessions are used to store user data and remember the user's state across requests.

Express.js provides a middleware called express-session for handling sessions. To use sessions in your application, you need to install and require the express-session middleware:

javascriptCopy code

const express = require('express'); const session = require('express-session'); const app = express(); app.use(session({    secret: 'secret-key',    resave: false,    saveUninitialized: true }));

In the above code, we have used the session middleware with a few options:

  • secret: A secret key used to sign the session ID cookie. You should set this to a random string.
  • resave: Forces the session to be saved back to the session store, even if the session was never modified during the request.
  • saveUninitialized: Forces a session that is "uninitialized" to be saved to the store.

Passport.js

Passport is a middleware that provides authentication for Node.js applications. It is designed to work with various authentication providers, including username and password, Facebook, Twitter, and many others.

To use Passport in your application, you need to install and require the passport and passport-local modules:

javascriptCopy code

const passport = require('passport'); const LocalStrategy = require('passport-local').Strategy;

The passport-local module provides a simple way to authenticate users with a username and password. It works by verifying the username and password against a database of users.

Once you have required the passport and passport-local modules, you need to configure Passport with a LocalStrategy:

javascriptCopy code

passport.use(new LocalStrategy(    function(username, password, done) {        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);        });    } ));

In the above code, we have created a new LocalStrategy and passed it a function that will be called when a user tries to authenticate.

Inside this function, we are using the findOne method of the User model to find a user with the given username. If the user is found, we are verifying the password using the verifyPassword method of the user model. If the password is correct, we are calling the done function with the user object, which will indicate that the authentication was successful.

If the authentication fails, we are calling the done function with false, which will indicate that the authentication failed.

After you have configured Passport, you need to use the passport.initialize() and passport.session() middleware in your application:

javascriptCopy code

app.use(passport.initialize()); app.use(passport.session());

passport.initialize() middleware initializes Passport and adds it to the request object. passport.session() middleware sets up Passport to use sessions to persist authenticated user data.

Once you have set up Passport, you can use the passport.authenticate() method to authenticate users in your application:

javascriptCopy code

app.post('/login', passport.authenticate('local'), function(req, res) {    res.redirect('/'); });

In the above code, we are using the passport.authenticate() method with the 'local' strategy to authenticate users.

35. Authentication Using Passport js

Comments: 2

profile
@niteshguptav63
17-Nov-2024, 01:39 PM

I am not able to access videos from second class and further. I have already completed first class

profile
@niteshguptav63
16-Nov-2024, 10:56 AM

When will I get my course?

profile
@admin79
17-Nov-2024, 01:29 PM

Now, Your query was resolved.

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?