🔐Implementing OAuth 2.0 and OpenID Connect for Secure Third-Party Authentication in Node.js Express
Introduction to OAuth 2.0 and OpenID Connect
OAuth 2.0 is an authorization framework that allows third-party applications to access limited resources on behalf of a user without exposing their credentials. OpenID Connect, on the other hand, is an identity layer built on top of OAuth 2.0, which provides authentication capabilities. By combining both, we can securely authenticate users and authorize access to protected resources.
In this article, I'll guide you through the process of implementing OAuth 2.0 and OpenID Connect in a Node.js Express application. We'll use Passport.js, a popular middleware for authentication, to streamline the process.
Prerequisites
Before diving in, make sure you have the following installed on your machine:
- Node.js (v14 or higher)
- npm (v6 or higher)
- A code editor, such as Visual Studio Code
Setting Up the Node.js Express Application
First, create a new directory for your project and navigate to it in your terminal. Then, initialize the project using npm:
mkdir oauth-openid-nodejs
cd oauth-openid-nodejs
npm init -y
Installing Dependencies
Now, let's install the required packages:
npm install express passport passport-openidconnect dotenv
Creating the Express Server
Create an index.js
file in the root of your project and add the following code to set up a basic Express server:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Welcome to the OAuth 2.0 and OpenID Connect demo!');
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
Setting Up Passport.js with OpenID Connect
Configuring Passport.js
First, create a .env
file in the root of your project and store your client ID, client secret, and callback URL. These will be provided by the third-party authentication provider you choose to work with (e.g., Google, Facebook, etc.):
CLIENT_ID=your_client_id
CLIENT_SECRET=your_client_secret
CALLBACK_URL=http://localhost:3000/auth/callback
Next, create a file named passport-setup.js
in the root of your project and add the following code to configure Passport.js with the OpenID Connect strategy:
const passport = require('passport');
const OidcStrategy = require('passport-openidconnect').Strategy;
const dotenv = require('dotenv');
dotenv.config();
passport.use(
new OidcStrategy(
{
issuer: 'https://your-auth-provider.com',
clientID: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
callbackURL: process.env.CALLBACK_URL,
scope: 'openid profile email'
},
(accessToken, refreshToken, profile, done) => {
return done(null, profile);
}
)
);
passport.serializeUser((user, done) => {
done(null, user);
});
passport.deserializeUser((user, done) => {
done(null, user);
});
module.exports = passport;
Replace https://your-auth-provider.com
with the appropriate issuer URL for your chosen authentication provider.
Updating the Express Server
Now, update your index.js
file to include Passport.js and the OpenID Connect configuration:
const express = require('express');
const passport = require('./passport-setup');
const session = require('express-session');
const app = express();
// Configure Express to use session middleware
app.use(session({
secret: 'your-session-secret',
resave: false,
saveUninitialized: true
}));
// Initialize Passport.js and session support
app.use(passport.initialize());
app.use(passport.session());
app.get('/', (req, res) => {
res.send('Welcome to the OAuth 2.0 and OpenID Connect demo!');
});
// Add route for OAuth 2.0 authentication
app.get('/auth', passport.authenticate('openidconnect'));
// Add route for OAuth 2.0 callback
app.get('/auth/callback',
passport.authenticate('openidconnect', { failureRedirect: '/login' }),
(req, res) => {
res.redirect('/profile');
}
);
// Add route for user profile
app.get('/profile', (req, res) => {
if (!req.user) {
return res.redirect('/login');
}
res.send(`Hello, ${req.user.displayName}!`);
});
// Add route for login page
app.get('/login', (req, res) => {
res.send('<a href="/auth">Log in with your Identity Providera>');
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
Testing the Application
Now, you're ready to test your Node.js Express application with OAuth 2.0 and OpenID Connect. Start the server by running:
node index.js
Visit http://localhost:3000/login
in your browser and click on the "Log in with your Identity Provider" link. You should be redirected to your authentication provider's login page. Once you've logged in, you should be redirected back to the /profile
route, where you'll see a personalized greeting with your display name.
Conclusion
In this article, we've demonstrated how to implement OAuth 2.0 and OpenID Connect in a Node.js Express application using Passport.js. This secure authentication method allows users to authenticate themselves without exposing their credentials to your application, resulting in a safer and more reliable authentication process.
Remember to replace the sample configuration details (issuer URL, client ID, client secret, etc.) with your actual authentication provider's information when deploying your application to production.
Mình hy vọng bạn thích bài viết này và học thêm được điều gì đó mới.
Donate mình một ly cafe hoặc 1 cây bút bi để mình có thêm động lực cho ra nhiều bài viết hay và chất lượng hơn trong tương lai nhé. À mà nếu bạn có bất kỳ câu hỏi nào thì đừng ngại comment hoặc liên hệ mình qua: Zalo - 0374226770 hoặc Facebook. Mình xin cảm ơn.
Momo: NGUYỄN ANH TUẤN - 0374226770
TPBank: NGUYỄN ANH TUẤN - 0374226770 (hoặc 01681423001)
All rights reserved