feat(auth): 添加第三方 token 验证功能
- 新增自定义中间件,用于解析和验证第三方 token - 添加 verifyThirdPartyToken 模块实现第三方 token 验证逻辑 - 成功验证后,将第三方 token 转换为 JWT token 并设置在请求头中 - 保护所有下方路由,确保只有有效 token 才能访问受保护资源
This commit is contained in:
20
app.js
20
app.js
@@ -6,7 +6,7 @@ const koaJwt = require("koa-jwt");
|
|||||||
const fs = require("fs");
|
const fs = require("fs");
|
||||||
const path = require("path");
|
const path = require("path");
|
||||||
const bodyParser = require("koa-bodyparser");
|
const bodyParser = require("koa-bodyparser");
|
||||||
|
const verifyThirdPartyToken = require("./auth/verifyThirdPartyToken");
|
||||||
const app = new Koa();
|
const app = new Koa();
|
||||||
app.use(bodyParser()); // 添加在路由中间件之前
|
app.use(bodyParser()); // 添加在路由中间件之前
|
||||||
const router = new Router();
|
const router = new Router();
|
||||||
@@ -40,6 +40,24 @@ router.post("/login", (ctx) => {
|
|||||||
ctx.body = { token };
|
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中间件(保护下方所有路由)
|
// JWT中间件(保护下方所有路由)
|
||||||
app.use(
|
app.use(
|
||||||
koaJwt({
|
koaJwt({
|
||||||
|
|||||||
3
auth/verifyThirdPartyToken.js
Normal file
3
auth/verifyThirdPartyToken.js
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
module.exports = token=>{
|
||||||
|
return {token}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user