Welcome to this comprehensive guide on implementing OAuth2 with Passport.js in your Node.js applications! In this tutorial, we'll explore how to use Passport.js to authenticate users using popular OAuth providers such as Google, Facebook, and GitHub.
OAuth2 is an open standard for authorization, allowing a user to grant a third-party application limited access to their resources without sharing their credentials. It's a common method used for authentication in modern web applications.
Passport.js is an authentication middleware for Node.js, providing a simple yet flexible framework for handling authentication strategies, including OAuth2.
Let's start by creating a new Node.js project and installing the necessary dependencies:
mkdir oauth-passport-demo
cd oauth-passport-demo
npm init -y
npm install express passport passport-google-oauth20 passport-facebook passport-github2Create a new file app.js and set up a basic Express server:
const express = require('express');
const app = express();
const port = 3000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});Initialize Passport.js, configure the strategy, and middleware for each provider:
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const FacebookStrategy = require('passport-facebook').Strategy;
const GitHubStrategy = require('passport-github2').Strategy;
// Google, Facebook, and GitHub credentials
// ...
passport.use(new GoogleStrategy({
// Google credentials
}, (accessToken, refreshToken, profile, done) => {
// Verify the accessToken and save the user in your database
done(null, profile);
}));
passport.use(new FacebookStrategy({
// Facebook credentials
}, (accessToken, refreshToken, profile, done) => {
// Verify the accessToken and save the user in your database
done(null, profile);
}));
passport.use(new GitHubStrategy({
// GitHub credentials
}, (accessToken, refreshToken, profile, done) => {
// Verify the accessToken and save the user in your database
done(null, profile);
}));Create routes for the login, callback, and logout endpoints:
app.get('/login/google', passport.authenticate('google', { scope: ['profile'] }));
app.get('/login/google/callback', passport.authenticate('google', { failureRedirect: '/login' }), (req, res) => {
// Successfully authenticated, save the user session, and redirect
});
app.get('/login/facebook', passport.authenticate('facebook', { scope: ['email'] }));
app.get('/login/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/login' }), (req, res) => {
// Successfully authenticated, save the user session, and redirect
});
app.get('/login/github', passport.authenticate('github'));
app.get('/login/github/callback', passport.authenticate('github', { failureRedirect: '/login' }), (req, res) => {
// Successfully authenticated, save the user session, and redirect
});Create a logout route to clear the session and redirect to the homepage:
app.get('/logout', (req, res) => {
req.logout();
res.redirect('/');
});Create a simple homepage for the application:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OAuth2 with Passport.js Demo</title>
</head>
<body>
<h1>Welcome to OAuth2 with Passport.js Demo</h1>
<!-- Add your navigation and content here -->
</body>
</html>To serve the homepage, set up Express to serve the public folder:
app.use(express.static('public'));Start the server and open your browser to http://localhost:3000:
node app.jsWhat is OAuth2 used for?
What is Passport.js?
Which of the following is NOT a popular OAuth provider supported by Passport.js?
That's it for the OAuth2 with Passport.js tutorial! With this knowledge, you can now secure your Node.js applications by implementing authentication using popular OAuth providers. Happy coding! 🎉🎊🎓