You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Strapi中所有用户均可修改其他用户的个人资料?

Strapi用户可修改其他用户资料的问题解决

这不是正常现象,Strapi默认的权限配置没有限制普通用户只能修改自身数据,需要手动调整权限逻辑,以下是两种解决方式:


方式一:自定义权限策略

  1. 创建自定义策略文件
    在config/policies(Strapi v4为src/policies)目录下新建isOwner.js,写入以下代码:

    module.exports = async (policyContext, config, { strapi }) => {
      const currentUserId = policyContext.state.user.id;
      const targetUserId = parseInt(policyContext.params.id, 10);
      // 仅允许操作自身数据
      return currentUserId === targetUserId;
    };
    
  2. 绑定策略到用户更新接口
    找到用户路由文件api/user/routes/user.js(v4为src/api/user/routes/user.js),修改PUT请求的路由配置,添加自定义策略:

    module.exports = {
      routes: [
        {
          method: 'PUT',
          path: '/users/:id',
          handler: 'user.update',
          config: {
            policies: ['isOwner'],
          },
        },
        // 其他路由保持不变
      ],
    };
    

方式二:修改控制器逻辑

直接在用户控制器中添加权限校验,找到api/user/controllers/user.js(v4为src/api/user/controllers/user.js),修改update方法:

module.exports = {
  async update(ctx) {
    const { id } = ctx.params;
    const currentUserId = ctx.state.user.id;

    // 校验是否为自身数据
    if (parseInt(id) !== currentUserId) {
      return ctx.forbidden('仅允许修改自身资料');
    }

    // 执行原更新逻辑
    const updatedUser = await strapi.service('api::user.user').update(
      id,
      ctx.request.body
    );
    return updatedUser;
  },
};

修改完成后重启Strapi服务,再次通过Swagger测试:使用用户5的token请求PUT /users/4时,会返回403禁止访问,符合预期权限控制。

内容的提问来源于stack exchange,提问作者Erfan Atp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 08:20:32