Auth0 Node.js/Express后端如何获取user.sub实现任务权限控制?
解决Auth0 JWT中user.sub的获取与任务归属匹配问题
核心逻辑
express-oauth2-jwt-bearer的checkJwt中间件会自动解析合法JWT,并将解析后的用户payload挂载到req.auth.payload对象上,你可以直接从中取出sub字段(即用户唯一标识),再通过参数化查询传递给SQL语句,既实现动态匹配用户任务,又避免SQL注入风险。
代码修改步骤
1. 调整task.controller.js,从JWT中读取用户ID
替换原来从URL参数获取userId的逻辑,改为从解析后的JWT payload中取值:
const Task = require("../models/task.model.js"); // Retrieve all Tasks from the database (user-specific) exports.findAll = (req, res) => { // 从JWT解析结果中获取用户sub值 const userId = req.auth.payload.sub; Task.getAll(userId, (err, data) => { if (err) res.status(500).send({ message: err.message || "Some error occurred while retrieving tasks." }); else res.send(data); }); };
2. 修改task.model.js,使用参数化查询
避免直接拼接SQL字符串,改用占位符?传递参数,彻底杜绝SQL注入:
const sql = require("./db.js"); // constructor const Task = function(task) { this.userId = task.userId; this.title = task.title; this.description = task.description; this.completed = task.completed; this.startDate = task.startDate; }; // Retrieve all Tasks for the authenticated user Task.getAll = (userId, result) => { // 用?作为参数占位符,避免字符串拼接 let query = `SELECT * FROM tasks WHERE userId = ?`; // 将userId作为参数数组传入,自动替换占位符 sql.query(query, [userId], (err, res) => { if (err) { console.log("error: ", err); result(null, err); return; } console.log("tasks: ", res); result(null, res); }); }; module.exports = Task;
3. 逻辑验证说明
checkJwt中间件会自动拦截无效JWT请求,无需额外处理- 合法请求中,
req.auth.payload.sub与你存储在tasks表的userId值完全匹配 - 参数化查询会自动处理字符串转义,避免恶意SQL注入攻击
内容的提问来源于stack exchange,提问作者alphatango165
相关产品推荐
相关产品推荐

