feat(auth): 添加第三方 token 验证功能

- 新增自定义中间件,用于解析和验证第三方 token
- 添加 verifyThirdPartyToken 模块实现第三方 token 验证逻辑
- 成功验证后,将第三方 token 转换为 JWT token 并设置在请求头中
- 保护所有下方路由,确保只有有效 token 才能访问受保护资源
This commit is contained in:
aixianling
2025-02-25 11:08:26 +08:00
parent 18eb590629
commit dc747d5d43
2 changed files with 22 additions and 1 deletions

20
app.js
View File

@@ -6,7 +6,7 @@ const koaJwt = require("koa-jwt");
const fs = require("fs");
const path = require("path");
const bodyParser = require("koa-bodyparser");
const verifyThirdPartyToken = require("./auth/verifyThirdPartyToken");
const app = new Koa();
app.use(bodyParser()); // 添加在路由中间件之前
const router = new Router();
@@ -40,6 +40,24 @@ router.post("/login", (ctx) => {
ctx.body = { token };
});
// 自定义中间件解析并验证第三方Token
app.use(async (ctx, next) => {
const authHeader = ctx.headers.authorization;
if (authHeader && authHeader.startsWith('Bearer ')) {
const thirdPartyToken = authHeader.split(' ')[1];
try {
// 这里假设第三方Token可以通过某种方式验证并转换为JWT Token
const decoded = verifyThirdPartyToken(thirdPartyToken); // 假设有一个验证函数
const jwtToken = jwt.sign(decoded, process.env.JWT_SECRET, { expiresIn: "1h" });
ctx.state.user = user; // 将用户信息存储在ctx.state中
ctx.headers.authorization = `Bearer ${jwtToken}`; // 替换为JWT Token
} catch (err) {
ctx.throw(401, 'Invalid third-party token');
}
}
await next();
});
// JWT中间件保护下方所有路由
app.use(
koaJwt({

View File

@@ -0,0 +1,3 @@
module.exports = token=>{
return {token}
}