Lập trình & API
20/10/2026
•
5 phút đọc
•
73 lượt xem
Hướng Dẫn Kết Nối Đăng Nhập Discord OAuth2 Cho Website Express.js Chuẩn Enterprise
S
Tác giả: Stain
Technical Administrator • SotarCloud
Xây dựng tính năng đăng nhập 1-Click bằng Discord qua giao thức OAuth2 Authorization Code Grant, bảo vệ phiên người dùng với cookie bảo mật và CSRF state.
# Hướng Dẫn Kết Nối Đăng Nhập Discord OAuth2 Cho Express.js
Đăng nhập bằng tài khoản mạng xã hội (Social Login) mang lại trải nghiệm tiện lợi vượt trội cho người dùng. Đặc biệt đối với các dịch vụ Gaming, Bot Hosting hay lập trình, **Discord OAuth2** là phương thức đăng nhập phổ biến và được yêu thích nhất.
Bài viết này hướng dẫn bạn cách tích hợp luồng **Authorization Code Grant** bảo mật vào ứng dụng Node.js Express.
---
## 1. Thiết Lập Ứng Dụng Trên Discord Developer Portal
1. Truy cập [Discord Developer Portal](https://discord.com/developers/applications) và tạo ứng dụng mới.
2. Chọn mục **OAuth2** trong thanh menu bên trái.
3. Trong mục **Redirects**, thêm URL callback của website:
```text
https://cloud.sotarstudio.online/auth/discord/callback
```
4. Lưu lại **Client ID** và **Client Secret**.
---
## 2. Triển Khai Mã Nguồn Trong Node.js / Express
```javascript
const express = require('express');
const router = express.Router();
const axios = require('axios');
const crypto = require('crypto');
const db = require('../db');
const CLIENT_ID = process.env.DISCORD_CLIENT_ID;
const CLIENT_SECRET = process.env.DISCORD_CLIENT_SECRET;
const REDIRECT_URI = 'https://cloud.sotarstudio.online/auth/discord/callback';
// 1. Chuyển hướng sang Discord
router.get('/auth/discord', (req, res) => {
const state = crypto.randomBytes(16).toString('hex');
req.session.oauth_state = state;
const discordUrl = `https://discord.com/api/oauth2/authorize?client_id=${CLIENT_ID}&redirect_uri=${encodeURIComponent(REDIRECT_URI)}&response_type=code&scope=identify%20email&state=${state}`;
res.redirect(discordUrl);
});
// 2. Tiếp nhận Callback
router.get('/auth/discord/callback', async (req, res) => {
const { code, state } = req.query;
if (!state || state !== req.session.oauth_state) {
return res.status(403).send('Yêu cầu không hợp lệ (Sai mã CSRF State)!');
}
delete req.session.oauth_state;
if (!code) return res.redirect('/login');
try {
// 3. Đổi authorization code lấy access_token
const tokenResponse = await axios.post(
'https://discord.com/api/oauth2/token',
new URLSearchParams({
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
grant_type: 'authorization_code',
code: code,
redirect_uri: REDIRECT_URI
}).toString(),
{ headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
);
const { access_token } = tokenResponse.data;
// 4. Lấy thông tin tài khoản
const userResponse = await axios.get('https://discord.com/api/users/@me', {
headers: { Authorization: `Bearer ${access_token}` }
});
const discordUser = userResponse.data;
// 5. Lưu phiên đăng nhập
req.session.user = {
username: discordUser.username,
discord_id: discordUser.id,
avatar: discordUser.avatar
? `https://cdn.discordapp.com/avatars/${discordUser.id}/${discordUser.avatar}.png`
: 'https://cdn.discordapp.com/embed/avatars/0.png'
};
return res.redirect('/dashboard');
} catch (err) {
console.error('Lỗi Discord OAuth2:', err.message);
res.redirect('/login?error=oauth_failed');
}
});
module.exports = router;
```
---
## 3. Bảo Vệ Phiên Làm Việc (Session Security)
- Luôn sử dụng `cookie: { secure: true, httpOnly: true, sameSite: 'lax' }` trên môi trường sản xuất.
- Lưu trữ session trong cơ sở dữ liệu (`express-mysql-session`) để phiên đăng nhập không bị thoát khi hệ thống cập nhật mã nguồn.
S
Tác giả: Stain
AdminChuyên gia phụ trách kỹ thuật và hạ tầng tại SotarCloud. Đam mê tối ưu hóa hiệu năng máy chủ Linux, phát triển Bot Discord quy mô lớn và phân giải DNS mạng Anycast.
Bài Viết Liên Quan
Discord Bot