【发布时间】:2022-08-14 03:15:42
【问题描述】:
- Strapi 版本:4.1.5
- 操作系统:Debian GNU/Linux 9
- 数据库:PostgreSQL 13
- 节点版本:v14.16.0
- NPM 版本:6.14.11
- 纱线版本:v1.22.5
大家好,我似乎找不到关于如何在 Strapi 中使用自定义插件的权限的一致信息。我想让一个端点对我的前端 (Next.JS) 应用程序可用,但前提是前端应用程序已作为用户进行身份验证并使用通过 Strapi 进行身份验证返回的 JWT。我不断收到401退货。
这就是我正在做的事情:
我使用this page 在 Strapi 中设置身份验证。我在 Strapi 中创建了一个用户,我可以从前端进行身份验证,它会返回一个 JWT 令牌。当我将集合类型设置为只能通过“已验证”角色访问时,我可以使用此 JWT 令牌在 api 中访问这些集合类型。所以所有这些都有效。问题是我无法让它与我的自定义插件一起使用,我不知道为什么。我仍然收到 401 错误。
以下是我设置权限的方式:
基于this page,我最初尝试利用已认证用户和权限插件提供的权限:
{
method: \"GET\",
path: \"/progress\",
handler: \"memberProgress.getProgress\",
config: {
policies: [\'plugins::users-permissions.isAuthenticated\']
},
},
不幸的是,这没有奏效。服务器报错,说找不到这个。所以回到上面链接的文档,我决定采用创建自己的全局权限的方法。我建立src/policies/is-authenticated.js内容如下:
module.exports = (policyContext, config, { strapi }) => {
if (policyContext.state.user) { // if a session is open
// go to next policy or reach the controller\'s action
return true;
}
return false; // If you return nothing, Strapi considers you didn\'t want to block the request and will let it pass
};
然后,我修改了插件的路由如下:
{
method: \"GET\",
path: \"/progress\",
handler: \"memberProgress.getProgress\",
config: {
policies: [\'global::is-authenticated\']
},
},
这一切都基于我链接到的那个文件。不幸的是,这仍然不起作用。它似乎找到了权限(服务器没有引发错误),但是当我尝试使用 JWT 令牌访问我的插件的端点时,我只收到 401 错误。
这是我尝试访问前端端点的方式:
// VERIFIED, auth works and I get the expected jwt
const strapiAuth = await strapiApiAuth();
if ( strapiAuth && strapiAuth.hasOwnProperty(\"jwt\") ) {
try {
const response = await axios.get(
`${process.env.STRAPI_BACKEND_URL}/member-progress/progress?year=2022&name=&pageSize=10&page=1`,
{
headers: {
Accept: \"application/json\",
Authorization: `Bearer ${strapiAuth.jwt}`
},
timeout: 500,
}
);
console.log(response);
} catch (error) {
// This is where I land with the 401 error
console.log(error);
}
}
标签: plugins next.js permissions strapi