自定义 Strapi 默认权限错误 return

Customize Strapi default permission error return

有没有办法通过 Strapi 编辑权限/令牌错误的默认错误 return?

例如,在 Public 角色下的角色和权限中,我取消选中 send-email-confirmation 的路由。如果我使用邮递员并尝试做 localhost:1337/auth/send-email-confirmation,我会得到这样的错误 return

{
    "statusCode": 403,
    "error": "Forbidden",
    "message": "Forbidden"
}

我相信这是默认的 middleware / policy 我知道我可以从哪里获得默认的 send-email-confirmation 控制器并对其进行编辑,但前提是 Roles & Permissions 在内部启用/选中 public角色。

与路由需要 headersAuthorization 令牌相同,但如果未提供,将再次给出默认错误,我无法找到自定义它的位置。

我似乎没有在 strapi 文档中找到它,或者我使用了错误的关键字进行搜索。

提前感谢您的任何建议。

auth 令牌 - 权限验证和错误在此文件中进行管理 - https://github.com/strapi/strapi/blob/0c6d39297f6f8a4f983e22fb48256b42da2a8605/packages/strapi-plugin-users-permissions/config/policies/permissions.js#L15

如果要更新此文件,则必须遵循自定义概念 - https://strapi.io/documentation/3.0.0-beta.x/concepts/customization.html#plugin-extensions

有了这个,您将能够更改错误消息。

创建自定义错误响应文件

在文件夹config/functions/responses/中,创建相应的文件,文件名与错误代码匹配。您可以在其中检查事件和 return 自定义响应。这适用于我使用 Strapi 3.6.8。我不确定最新的 Strapi。 Here's an older doc page 以错误代码作为参考。

为各种错误代码创建这种格式的文件...

示例:

config/functions/responses/404.js

'use strict'

module.exports = async (ctx) => {

    // Do other stuff
    console.log("404 response is: %O, ctx)

    // Return a specific error format (e.g. 'notFound') with your own custom message
    return ctx.notFound('My custom 404 message')

}

config/functions/responses/403.js

'use strict'

module.exports = async (ctx) => {

    // Do other stuff
    console.log("403 response is: %O, ctx)

    // Return a specific error format (e.g. 'forbidden') with your own custom message
    return ctx.forbidden('My custom 403 message')

}