大家好,我似乎找不到关于如何在Strapi中使用自定义插件的权限的一致信息。我希望使前端(Next.JS)应用程序可以使用端点,但前提是前端应用程序已经作为用户进行了身份验证,并且使用了使用Strapi身份验证后返回的JWT。我不断得到401美元的回报。
,我正在做的事情是:
我使用此页在Strapi中设置身份验证。我在Strapi中创建了一个用户,在前端,我可以进行身份验证,并返回一个JWT令牌。当我将集合类型设置为只能使用“身份验证”角色访问时,我可以使用这个JWT令牌访问api中的那些集合类型。所以所有这些都有效。问题是,我无法让它与我的自定义插件工作,我不知道为什么。我仍然得到401错误,而不是。
,下面是我如何设置权限:
基于此页,我最初尝试利用用户和权限插件提供的isAuthenticated权限:
{
method: "GET",
path: "/progress",
handler: "memberProgress.getProgress",
config: {
policies: ['plugins::users-permissions.isAuthenticated']
},
},
不幸的是,这是行不通的。服务器引发一个错误,表示无法找到此错误。因此,回到上面链接的文档,我决定采用创建自己的gloabl许可的方法。我创建了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);
}
}
发布于 2022-08-13 19:15:42
Strapi检查默认情况下是否有一个带有“身份验证”角色的有效jwt,但您必须在管理面板的“设置→用户&权限插件→角色”中标记对自定义端点的权限。
https://stackoverflow.com/questions/72610443
复制相似问题