为什么 Strapi 中的所有用户都有权更新所有用户的个人资料?

Erf*_*Atp 1 javascript backend node.js strapi

我向用户模型添加了一个名为 config (类型:json)的新文件。我使用Strapi本地文档内置的swagger 。问题是我可以使用 put 方法更新另一个用户配置(数据)。

  1. 首先,我授权POST /auth/local并获取我的令牌和用户 ID(在此转换中为 5)
  2. 我将令牌添加到 swagger 授权按钮。
  3. 然后,我PUT /user/{id}在本例中使用的 id 是 5。
  4. 调用apihttp://localhost:1337/api/users/4返回200!

我预计会收到 403 错误!因为我不应该能够更改其他用户配置文件!正常吗?如果是,请告诉我解决此问题的解决方案。

ant*_*hio 6

这是因为 Strapi 只有两个默认角色:

  • 民众
  • 已认证

因此,默认情况下,当您设置权限时,无论当前用户处于何种身份验证状态,都可以相应地访问所有内容(例如,公开到仅公开、已验证到已验证)

要处理此问题,并限制身份验证范围内的用户操作,您必须使用中间件或策略,因此由于这是在用户权限范围内,让我们将策略添加到用户权限中:

斯特皮4.5.3

yarn strapi generate

? Strapi Generatos
>policy

? Policy name 
isOwner

? Where do you want to add this policy?
> Add policy to root of project
Run Code Online (Sandbox Code Playgroud)

下一步是在您的/src/extensions文件夹中创建文件夹users-permissions,并在此文件夹中创建strapi-server.js包含以下内容的文件:

/src/extensions/users-permissions/strapi-server.js

module.exports = (plugin) => {
  for (let i = 0; i < plugin.routes["content-api"].routes.length; i++) {
    const route = plugin.routes["content-api"].routes[i];
    if (
      route.method === "GET" &&
      route.path === "/users/:id" &&
      route.handler === "user.findOne"
    ) {
      console.log(route);
      plugin.routes["content-api"].routes[i] = {
        ...route,
        config: {
          ...route.config,
          policies: route.config.policies
            ? [...route.config.policies, "global::isOwner"] // tests if policies were defined
            : ["global::isOwner"],
        },
      };
    }
  }

  return plugin;
};

Run Code Online (Sandbox Code Playgroud)

如果您在 Strapi 服务器控制台中执行了正确的步骤,您必须看到: info: In isOwner policy.如果您将 get 请求发送到 /api/users/:id

下一步我们将修改策略文件,如下所示: /src/policies/isOwner.js

"use strict";

/**
 * `isOwner` policy
 */

module.exports = async (policyContext, config, { strapi }) => {
  strapi.log.info("In isOwner policy.");
  const { user, auth } = policyContext.state;
  const { params } = policyContext;

  // this case the userId is the same as the id we are requesting
  // other cases would need more extensive validation...
  const canDoSomething = user.id == params.id;

  if (canDoSomething) {
    return true;
  }

  return false;
};
Run Code Online (Sandbox Code Playgroud)

和哇拉:

{
    "data": null,
    "error": {
        "status": 403,
        "name": "PolicyError",
        "message": "Policy Failed",
        "details": {}
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我们尝试获取其他用户个人资料

带中间件的版本当前用户的私有 Strapi 数据