gpt4 book ai didi

strapi - 如何以经过身份验证的用户身份使用 GraphQL 查询 Strapi 后端?

转载 作者:行者123 更新时间:2023-12-04 15:40:09 26 4
gpt4 key购买 nike

目前,我只能以公共(public)用户身份运行查询,Strapi 会为我获取结果。但是,我想完全阻止对公共(public)用户的所有查询访问,只允许经过身份验证的用户(最好只允许一个特定用户)。

我知道我可以在 Roles & Permissions 插件中阻止查询访问,我也知道可以在 Content Types -> Users< 中使用自己的密码创建一个新用户/strong> 屏幕。其实我已经有了,它叫web。现在,如何以该特定用户身份在我的 /graphql/ 端点中执行查询?

最佳答案

GraphQL 端点不是通过 route 管理的,而是通过中间件管理的。所以政策体系不适用。

您将无法删除对此端点的访问权限。但是您可以通过更新 GraphQL 配置文件来禁用 GraphQL Playground GET/graphql。这是执行此操作的文档 https://strapi.io/documentation/3.0.0-beta.x/guides/graphql.html#configurations

如果你想限制对 GraphQL 端点的访问,我建议你创建一个新的中间件,它将检查触发的端点是否是 /graphql 并检查经过身份验证的用户是否是你想要的。

这是创建中间件的文档 https://strapi.io/documentation/3.0.0-beta.x/advanced/middlewares.html

你的中间件看起来像那样

module.exports = strapi => {
return {
initialize() {
strapi.app.use(async (ctx, next) => {
const handleErrors = (ctx, err = undefined, type) => {
if (ctx.request.graphql === null) {
return (ctx.request.graphql = strapi.errors[type](err));
}

return ctx[type](err);
};

// check if it's a graphql request
if (ctx.request.url === '/graphql' && ctx.request.method === 'POST') {
if (ctx.request && ctx.request.header && ctx.request.header.authorization) {
try {
// get token data
const { id } = await strapi.plugins[
'users-permissions'
].services.jwt.getToken(ctx);

if (id === undefined) {
throw new Error('Invalid token: Token did not contain required fields');
}

// check if the id match to the user you want
if (id !== 'my-user-id') {
return handleErrors(ctx, 'You are not authorized to access to the GraphQL API', 'unauthorized');
}
} catch (err) {
return handleErrors(ctx, err, 'unauthorized');
}
} else {
// if no authenticated, return an error
return handleErrors(ctx, 'You need to be authenticated to request GraphQL API', 'unauthorized');
}
}

await next();
});
}
};
};

此代码将限制 my-user-id 对您的 GraphQL API 的访问。

要进行身份验证,您必须在 header 中发送 JWT。请按照此处的文档了解它https://strapi.io/documentation/3.0.0-beta.x/guides/authentication.html

关于strapi - 如何以经过身份验证的用户身份使用 GraphQL 查询 Strapi 后端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58096203/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com