我使用此处概述的方法成功验证了对 KeystoneJS API 的用户请求。
但是,我需要向我的应用程序添加一个自定义快速端点,该端点只能由请求标头中具有有效令牌的用户访问(请参阅之前的答案)。
我一直在挖掘有关会话和中间件的 Keystone 文档,但这不是我的专业领域,我无法弄清楚请求令牌是如何验证的。
如何验证对自定义端点的
GET
请求的授权标头中的令牌?意识到这可能与 Express 和会话管理有关,而不是专门与 Keystone 有关。
假设采用标准设置,可以将以下内容添加到
configureExpress
(请参阅此处),以将 Keystone 会话中间件应用到自定义 Express 端点:
app.use('/myEndpoint', keystone._sessionManager.getSessionMiddleware({ keystone }));
然后:
const whitelist = ['http://localhost:4200'];
const corsOptions = {
origin: function (origin, callback) {
if (whitelist.indexOf(origin) !== -1 || !origin) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
}
}
app.post('/myEndpoint', cors(corsOptions), (req, res) => {
if (req.user) {
// User is authorised
res.send(req.user);
} else {
res.status(401).send()
}
});
注释/陷阱:
POST
请求必须包含 GraphQL 查询,以对您的用户进行身份验证sessionStore
- 请参阅此处我使用的是 Keystone.js 版本 6。在此版本中,您可以通过为请求创建上下文并使用 Keystone 提供的查询 API 将自定义 REST 端点添加到服务器:
export default config<TypeInfo>({
server: {
extendExpressApp: (app, commonContext) => {
app.get('/api/users', async (req, res) => {
const context = await commonContext.withRequest(req, res);
res.json({
session: context.session ?? "",
});
});
},
},
});
const myHeaders = new Headers();
myHeaders.append("Authorization", "****");
fetch("http://localhost:3001/test", {
method: "POST",
headers: myHeaders,
redirect: "follow"
})
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.error(error));
{
"session": {
"listKey": "User",
"itemId": "f488d9ef-c23e-4009-8b5a-f54b02e38e90",
"data": {
"name": "Ali Hesari",
"createdAt": "2024-06-21T22:20:03.722Z",
"isAdmin": true
}
}
}