Hi, I'm Tuan, a Full-stack Web Developer from Tokyo 😊. Follow my blog to not miss out on useful and interesting articles in the future.
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, we'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.
And Finally
As always, I hope you enjoyed this article and got something new. Thank you and see you in the next articles!
If you liked this article, please give me a like and subscribe to support me. Thank you. 😊