- vừa được xem lúc

Blog#200: 🔐Implementing OAuth 2.0 and OpenID Connect for Secure Third-Party Authentication in Node.js Express

0 0 24

Người đăng: NGUYỄN ANH TUẤN

Theo Viblo Asia

200

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, 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.

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. 😊

Ref

Bình luận

Bài viết tương tự

- vừa được xem lúc

Cách mình "hack" được vào hẹ thống của SMAS để xem điểm.

Cách mà mình "hack" được vào hệ thống của SMAS. Thật ra dùng từ hack cũng không đúng lắm, chỉ là một vài trick để lừa hệ thống mà thôi.

0 0 146

- vừa được xem lúc

[NodeJs] Tạo QR Code trong nodeJs với qrcode

Tạo mã QR Code trong nodejs với qrcode. QR Code là gì. Tạo QR code với qrcode. Cài đặt thư viện qrcode.

0 0 34

- vừa được xem lúc

Áp dụng kiến trúc 3 Layer Architecture vào project NodeJS

The problem encountered. Các framework nodejs phổ biết như Express cho phép chúng ta dễ dàng tạo ra Resful API xử lí các request từ phía client một cách nhanh chóng và linh hoạt.

0 0 80

- vừa được xem lúc

Router, Controller trong Express

Mở đầu. Xin chào các bạn mình đã quay trở lại rồi đây, tiếp tục với series Nodejs cơ bản thì hôm nay mình sẽ giới thiệu đến các bạn Express Router và Controller.

0 0 43

- vừa được xem lúc

Xây dựng CRUD RESTful API sử dụng Node, Express, MongoDB.

Introduction. Trong phạm vi bài viết này chúng ta sẽ cùng tìm hiểu về cách tạo restful api với Node, Express và MongoDB. . Xử lý các hoạt động crud.

0 0 226

- vừa được xem lúc

Rate time limit trong NodeJS

Chào các bạn, lại là mình đây. Hôm nay mình xin giới thiệu tới các bạn một kỹ thuật rất hay ho và hữu ích đó là Rate Limiting. 1. Rate Limiting là gì.

0 0 64