角色鉴权代码报错:Cannot read properties of null (reading 'role')
角色授权中间件报错排查:Cannot read properties of null (reading 'role')
问题场景
我编写了用于角色授权的中间件代码:
exports.authorizeRoles = (...Roles)=>{ return (req,res,next)=>{ if(!Roles.includes(req.user.role)){ next(new ErrorHander(`Role ${req.user.role} is not allowed to accsess this resource`,403)) } next(); } }
使用Postman测试API时,触发如下错误:
{ "success": false, "message": "Cannot read properties of null (reading 'role')" }
错误原因
- 核心问题是
req.user的值为null,导致无法读取role属性。这说明在执行authorizeRoles授权中间件前,用户身份验证环节未正确完成,没有将用户信息挂载到req.user对象上。 - 具体诱因包括:
- 身份验证中间件(如JWT校验)未在
authorizeRoles之前执行 - 身份验证中间件执行失败后,未拦截请求直接进入了授权逻辑
- 请求未携带有效身份凭证(如token),导致身份验证不通过,
req.user未被初始化
- 身份验证中间件(如JWT校验)未在
解决方法
调整中间件执行顺序
在路由配置中,必须将身份验证中间件放在authorizeRoles之前,确保先完成用户身份校验并挂载req.user,再执行授权逻辑:// 示例路由配置 router.get('/admin/dashboard', authMiddleware, authorizeRoles('admin'), dashboardController);完善身份验证中间件的错误拦截
身份验证失败时,直接返回错误响应,避免请求流入授权中间件:const authMiddleware = (req, res, next) => { const token = req.headers.authorization?.split(' ')[1]; if (!token) { return res.status(401).json({ success: false, message: '未提供有效身份凭证' }); } try { const decoded = jwt.verify(token, process.env.JWT_SECRET); req.user = decoded; // 将解析后的用户信息挂载到req.user next(); } catch (err) { return res.status(401).json({ success: false, message: '身份凭证无效或已过期' }); } };在授权中间件中增加前置校验
为避免req.user为null的情况,在授权逻辑前先检查用户是否已完成身份验证:exports.authorizeRoles = (...Roles)=>{ return (req,res,next)=>{ if(!req.user){ return next(new ErrorHander('请先完成身份验证',401)); } if(!Roles.includes(req.user.role)){ next(new ErrorHander(`Role ${req.user.role} is not allowed to access this resource`,403)) } next(); } }同时注意修正代码拼写错误:将
accsess改为access。
内容的提问来源于stack exchange,提问作者Yadav Karishma
相关产品推荐
相关产品推荐

