Passport.js is a widely used middleware for Node.js applications that provides authentication support. It has become popular due to its flexibility, ease of use, and the wide range of authentication strategies it offers. In this article, we will dive into what Passport.js is, how it works, and some of its features.
About Passport.js:
Passport.js is a middleware that provides authentication support for Node.js web applications. It enables developers to authenticate users through a range of authentication strategies, including traditional username and password authentication, social media authentication, OAuth, OpenID, and more. The Node.js platform builds Passport.js, and the project is available as an open-source under the MIT license.
How does Passport.js work?
Passport.js works by using a set of “strategies” to authenticate users. A strategy is a set of rules that define how a user is authenticated.
For instance, the local strategy involves verifying a user’s identity by checking their username and password credentials against a database of registered users. Passport.js offers a range of strategies, and developers can also create their own custom strategies.
Passport.js divides the authentication process into three main steps: configuration, routing, and verification.
- Configuration: The first step in using Passport.js is to configure the authentication strategies that will be used. Passport.js requires the installation of the appropriate authentication strategies for the application.
- Routing: The second step is to define the routes for authentication. Passport.js provides several routes to handle authentication, such as routes for logging in, logging out, and registering a new user.
- Verification: The third step is to verify the user’s identity. Passport.js handles the verification of user credentials by calling the appropriate strategy’s verify function. Once the user is authenticated, Passport.js sets a session cookie to maintain the user’s authentication status.
What are the features of Passport.js?
- Flexibility: Passport.js is a very flexible middleware that supports a wide range of authentication strategies. This makes it suitable for almost any authentication scenario.
- Simplicity: Passport.js is easy to use and integrates seamlessly with Node.js web applications. It requires minimal setup and configuration.
- Customizable: Passport.js allows developers to create their own custom authentication strategies to suit their specific authentication needs.
- Session management: Passport.js provides support for session management, allowing web applications to keep track of a user’s authentication status throughout their session.
- Security: Passport.js is designed with security in mind. It provides a secure and reliable authentication system that helps to protect against common authentication attacks.
Create a Google login with Passport.js
To create a Google auth login with Passport.js, you will need to follow these steps:
Step 1:
Set up a Google API Console project and obtain a client ID and secret.
The first step is to create a Google API Console project and obtain a client ID and secret. To do this, follow these steps:
- Go to the Google API Console: https://console.developers.google.com/
- Create a new project by clicking the “Create Project” button in the top right corner.
- Enter a project name and click “Create”.
- On the dashboard, click “Enable APIs and Services”.
- Search for “Google+ API” and click on it.
- Click the “Enable” button.
- Go to the “Credentials” section and click “Create Credentials” > “OAuth client ID”.
- Choose “Web application” as the application type and enter a name for your OAuth client.
- In the “Authorized JavaScript origins” field, enter the URL of your web application.
- In the “Authorized redirect URIs” field, enter the callback URL of your authentication route (e.g., http://localhost:3000/auth/google/callback).
- Click “Create” to generate your client ID and secret.
Step 2:
Install the passport-google-oauth2 package
Next, install the passport-google-oauth2 package using npm:
npm install passport-google-oauth2
Step 3:
Configure Passport.js with Google authentication strategy.
In your Node.js application, configure Passport.js with the Google authentication strategy by requiring the passport-google-oauth2 package and creating a new instance of the GoogleStrategy class:
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth2').Strategy;
passport.use(new GoogleStrategy({
clientID: 'YOUR_CLIENT_ID',
clientSecret: 'YOUR_CLIENT_SECRET',
callbackURL: 'http://localhost:3000/auth/google/callback'
}, (accessToken, refreshToken, profile, done) => {
// Verify the user and call done() with user data
}));
Replace YOUR_CLIENT_ID
and YOUR_CLIENT_SECRET
with your Google client ID and secret obtained in step 1.
Step 4:
Define the authentication routes
app.get('/auth/google', passport.authenticate('google', {
scope: ['profile', 'email']
}));
app.get('/auth/google/callback', passport.authenticate('google', {
failureRedirect: '/login'
}), (req, res) => {
// Successful authentication, redirect home.
res.redirect('/');
});
app.get('/logout', (req, res) => {
req.logout();
res.redirect('/');
});
The first route, /auth/google
, initiates the Google authentication process by redirecting the user to the Google login page. The scope
the parameter specifies the Google API access permissions that your application requires (in this case, profile
and email
).
The second route, /auth/google/callback
, handles the Google authentication callback by verifying the user’s credentials and redirecting the user to the home page.
The third route, /logout
, logs the user out of the application.
Step 5:
Protect the routes that require authentication.
Finally, protect the routes that require authentication by checking whether the user is logged in:
app.get('/', (req, res) => {
if (req.isAuthenticated()) {
res.send('Hello, ' + req.user.displayName + '!');
} else {
res.redirect('/login');
}
});
app.get('/profile', isAuthenticated, (req, res) => {
res.send('Welcome to your profile, ' + req.user
Create a Microsoft login with Passport.js
To create a Microsoft login with Passport.js, you will need to follow these steps:
Step 1: Register your application with the Microsoft Azure portal
The first step is registering your application with the Microsoft Azure portal and obtaining a client ID and secret. To do this, follow these steps:
- Go to the Azure portal: https://portal.azure.com/
- Click “Azure Active Directory” in the left-hand menu.
- Click “App registrations”.
- Click “New registration”.
- Enter a name for your application and select “Accounts in any organizational directory (Any Azure AD directory – Multitenant)” as the “Supported account types”.
- Enter the redirect URI for your authentication route (e.g., http://localhost:3000/auth/microsoft/callback).
- Click “Register” to generate your client ID and secret.
Step 2: Install the passport-azure-ad package
npm install passport-azure-ad
Step 3: Configure Passport.js with Microsoft authentication strategy
In your Node.js application, configure Passport.js with the Microsoft authentication strategy by requiring the passport-azure-ad package and creating a new instance of the OIDCStrategy class:
const passport = require('passport');
const OIDCStrategy = require('passport-azure-ad').OIDCStrategy;
passport.use(new OIDCStrategy({
identityMetadata: 'https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration',
clientID: 'YOUR_CLIENT_ID',
clientSecret: 'YOUR_CLIENT_SECRET',
responseType: 'code',
responseMode: 'form_post',
redirectUrl: 'http://localhost:3000/auth/microsoft/callback',
scope: ['openid', 'profile', 'email']
}, (accessToken, refreshToken, profile, done) => {
// Verify the user and call done() with user data
}));
Replace YOUR_CLIENT_ID
and YOUR_CLIENT_SECRET
with your Microsoft client ID and secret obtained in step 1.
Step 4: Define the authentication routes
app.get('/auth/microsoft', passport.authenticate('azuread-openidconnect', {
failureRedirect: '/login'
}));
app.post('/auth/microsoft/callback', passport.authenticate('azuread-openidconnect', {
failureRedirect: '/login'
}), (req, res) => {
// Successful authentication, redirect home.
res.redirect('/');
});
app.get('/logout', (req, res) => {
req.logout();
res.redirect('/');
});
The first route, /auth/microsoft
, initiates the Microsoft authentication process by redirecting the user to the Microsoft login page.
The second route, /auth/microsoft/callback
, handles the Microsoft authentication callback by verifying the user’s credentials and redirecting the user to the home page.
The third route, /logout
, logs the user out of the application.
Step 5: Protect the routes that require authentication
Finally, protect the routes that require authentication by checking whether the user is logged in:
app.get('/', (req, res) => {
if (req.isAuthenticated()) {
res.send('Hello, ' + req.user.displayName + '!');
} else {
res.redirect('/login');
}
});
app.get('/profile', isAuthenticated, (req, res) => {
res.send('Welcome to your profile, ' + req.user.displayName + '!');
});
function isAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect('/login');
}
The isAuthenticated
the function checks whether the user is authenticated and redirects
Conclusion:
Passport.js is a powerful and flexible authentication middleware for Node.js web applications. It simplifies the authentication process, making it easier for developers to create secure and reliable web applications. With its wide range of authentication strategies, Passport.js is suitable for almost any authentication scenario, and its support for session management ensures that users remain authenticated throughout their session.
Follow Us on
https://www.linkedin.com/company/scribblers-den/
Read More
https://scribblersden.com/what-is-gpt4/
Thank You
very helpful for developers