简体   繁体   English

如何定期获取远程公钥并存储在 Apollo graphql 服务器中?

[英]How to grab remote public key and store in Apollo graphql server periodically?

I have run an Apollo graphql server.我已经运行了 Apollo graphql 服务器。 I want to verify JWT sent by Firebase client.我想验证 Firebase 客户端发送的 JWT。 According to this document we can fetch public keys to verify.根据这个文档,我们可以获取公钥进行验证。 It also gives max-age until which we can store the key.它还给出了max-age直到我们可以存储密钥。 I use Auth0-nodejs for JWT verification.我使用 Auth0-nodejs 进行 JWT 验证。 My problem is how do I periodically fetch this public key and store in nodejs variable in Apollo server so that I don't have to fetch keys from firebase for every request in the apollo server.我的问题是如何定期获取此公钥并将其存储在 Apollo 服务器的 nodejs 变量中,以便我不必为 apollo 服务器中的每个请求从 firebase 获取密钥。

const server = new ApolloServer({
schema, context: ({ req }) => {
const token = req.headers.authorization;
const user = getAuthorizedUser(token);
return { user };
}
});

server.listen();

Here getAuthorizedUser(token) needs to grab the public keys from remote server every time on new request.这里 getAuthorizedUser(token) 每次收到新请求时都需要从远程服务器获取公钥。 This may slow down my app.这可能会减慢我的应用程序的速度。 I am not sure how can I periodically fetch data from remote server and use it for every request on my server.我不确定如何定期从远程服务器获取数据并将其用于服务器上的每个请求。

You could just fetch them lazily.你可以懒洋洋地取它们。 Something like:就像是:

let keys
let expiresAt = 0

async function getPublicKeys () {
  if (expiresAt < Date.now()) {
    try {
      const { maxAge, publicKeys } = await getKeysFromFirebase()
    catch (e) {
      // Handle being unable to fetch the keys from Google -- either retry or throw
    }
    expiresAt = (maxAge * 1000) + Date.now() - arbitraryPadding
    keys = publicKeys
  }
  return keys
}

Barring that, you could have your application refetch them before they expire using setTimeout -- you would just need to ensure that your timer is cleared when the process exits.除此之外,您可以让您的应用程序在它们过期之前使用setTimeout重新获取它们——您只需要确保在进程退出时清除您的计时器。 You could also set up a cron job that would just periodically write the keys to file.您还可以设置一个 cron 作业,它会定期将密钥写入文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM