diff --git a/app.js b/app.js index d7984f0..aa15250 100644 --- a/app.js +++ b/app.js @@ -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({ diff --git a/auth/verifyThirdPartyToken.js b/auth/verifyThirdPartyToken.js new file mode 100644 index 0000000..018e478 --- /dev/null +++ b/auth/verifyThirdPartyToken.js @@ -0,0 +1,3 @@ +module.exports = token=>{ + return {token} +} \ No newline at end of file