在开发过程中,用户身份验证是确保系统安全性和数据完整性的关键环节。Egg.js 是一个基于 Koa 的企业级 Node.js 框架,它提供了丰富的插件和中间件来帮助开发者构建高性能的应用。本文将为你详细介绍如何使用 Egg.js 设置 token,以实现用户身份验证。
步骤一:安装 Egg.js 和依赖包
首先,你需要确保你的项目中已经安装了 Egg.js。可以通过以下命令来创建一个新的 Egg.js 项目:
npm init egg --type=simple
cd your-project-name
npm install
在项目中,你还需要安装 token 相关的依赖包,如 jsonwebtoken:
npm install jsonwebtoken --save
步骤二:配置 Egg.js 以支持 token
在 config/config.default.js 文件中,配置 token 的相关参数,例如过期时间等:
module.exports = {
// 其他配置...
jwt: {
secret: 'your-secret-key', // 用于签名和解密的密钥
expiresIn: '1h', // token过期时间,例如1小时
},
};
步骤三:创建中间件进行 token 验证
创建一个中间件 token_auth.js 来验证用户请求中的 token:
// middleware/token_auth.js
const jwt = require('jsonwebtoken');
module.exports = (options, app) => {
return async function tokenAuth(ctx, next) {
const token = ctx.headers.authorization;
if (!token) {
return ctx.fail(401, 'Missing token');
}
try {
const decoded = jwt.verify(token, app.config.jwt.secret);
ctx.user = decoded; // 将解码后的用户信息存入 ctx 中
} catch (err) {
return ctx.fail(403, 'Invalid token');
}
await next();
};
};
步骤四:使用中间件保护路由
在路由配置中,使用上面创建的中间件来保护你的路由:
// router.js
const { controller, router } = require('@koa/router');
const TokenAuth = require('../middleware/token_auth');
router.get('/protected', TokenAuth(), controller('protected').index);
module.exports = router;
步骤五:生成和返回 token
在用户登录成功后,你可以使用 jsonwebtoken 库来生成一个 token 并返回给客户端:
// controller/login.js
const jwt = require('jsonwebtoken');
module.exports = {
async index(ctx) {
// 登录验证逻辑...
const token = jwt.sign(
{ userId: user.id, username: user.username },
ctx.app.config.jwt.secret,
{ expiresIn: ctx.app.config.jwt.expiresIn }
);
ctx.body = {
message: 'Login success',
token,
};
},
};
通过以上五个步骤,你就可以在 Egg.js 应用中轻松实现用户身份验证了。记得在实际开发中,要妥善保管密钥,并考虑使用 HTTPS 等安全措施来保护你的 token。
