0%

api-登陆注册接口

记录基于 Express 的用户注册与登录接口实现,使用了 bcrypt 进行密码加密,JWT(jsonwebtoken)进行登录状态的令牌管理,并结合环境变量安全存储密钥。


环境准备

  • Node.js
  • Express 框架
  • bcrypt:密码哈希加密
  • jsonwebtoken:JWT 令牌生成
  • Sequelize 模型定义
  • dotenv:管理环境变量(SECRET_KEY)

1. 环境变量配置

在项目根目录创建 .env 文件,写入如下内容:

1
SERVER_TOOLS_LOGIN_SECRET=jwt_secret_key(自定义密钥)

注意: 请使用足够复杂且随机的密钥,确保安全。

在项目入口文件(如 app.jsserver.js)中添加:

1
require('dotenv').config();

2.引入示例

路由脚本(User.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
const express = require('express');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const { Users } = require('../MySQL/db'); // 根据实际路径调整
const router = express.Router();

const SALT_ROUNDS = 10;
const SECRET_KEY = process.env.SERVER_TOOLS_LOGIN_SECRET; //引入定义的密钥

if (!SECRET_KEY) {
throw new Error('缺少 JWT 密钥,请检查环境变量配置');
}

// 用户注册接口
router.post('/register', async (req, res) => {
const { username, password, role } = req.body;
if (!username || !password) {
return res.status(400).json({ success: false, message: '用户名和密码不能为空' });
}

try {
const exists = await Users.findOne({ where: { username } });
if (exists) {
return res.status(409).json({ success: false, message: '用户名已存在' });
}

const hash = await bcrypt.hash(password, SALT_ROUNDS);
const newUser = await Users.create({
username,
password: hash,
role: role || 'user'
});

res.json({ code: 20000, success: true, message: '注册成功', userId: newUser.id });
} catch (err) {
console.error('注册出错:', err);
res.status(500).json({ success: false, message: '服务器错误' });
}
});

// 用户登录接口
router.post('/login', async (req, res) => {
const { username, password } = req.body;
if (!username || !password) {
return res.status(400).json({ success: false, message: '用户名和密码不能为空' });
}

try {
const user = await Users.findOne({ where: { username } });
if (!user) {
return res.status(401).json({ success: false, message: '用户名不存在' });
}

const valid = await bcrypt.compare(password, user.password);
if (!valid) {
return res.status(401).json({ success: false, message: '密码错误' });
}

const token = jwt.sign({ id: user.id, role: user.role }, SECRET_KEY, { expiresIn: '7d' });

res.json({
code: 20000,
success: true,
message: '登录成功',
token,
user: {
id: user.id,
username: user.username,
role: user.role
}
});
} catch (err) {
console.error('登录出错:', err);
res.status(500).json({ success: false, message: '服务器错误' });
}
});

module.exports = router;

依赖项安装:

1
2
yarn add express bcrypt jsonwebtoken
yarn add dotenv

主程序(app.jsserver.js)

1
2
3
4
5
require('dotenv').config();
const userRouter = require('./routes/Users');
app.use(express.json());
app.use(cors());
app.use('/Users', userRouter);

3. 关键点说明

  • 密码加密:使用 bcrypt 的 hashcompare 方法确保密码安全存储和验证。
  • JWT 生成:登录成功后,使用密钥生成包含用户ID和角色的 JWT,过期时间7天。
  • 环境变量管理密钥:通过 process.env.SERVER_TOOLS_LOGIN_SECRET 读取,避免密钥硬编码。
  • 错误处理:注册、登录过程均包含参数校验和异常捕获,保证接口稳定。

4. 使用建议

  • .env 文件请加入 .gitignore,避免泄漏密钥。
  • 生产环境建议通过服务器环境变量注入密钥,而非文件。
  • 根据需求扩展接口权限验证及用户信息管理。

-------------本文结束感谢您的阅读-------------