繁体   English   中英

使用 Firebase 可调用函数发送 cookie 作为响应

[英]Sending a cookie as a response with Firebase Callable Functions

我正在尝试使用 Firebase 可调用云函数(https.onCall)发送一个带有选项的 cookie 作为响应。 我在Firebase 文档中看到这可以通过 express 完成:(以下内容直接取自Firebase 文档

app.post('/sessionLogin', (req, res) => {
  // Get the ID token passed and the CSRF token.
  const idToken = req.body.idToken.toString();
  const csrfToken = req.body.csrfToken.toString();
  // Guard against CSRF attacks.
  if (csrfToken !== req.cookies.csrfToken) {
    res.status(401).send('UNAUTHORIZED REQUEST!');
    return;
  }
  // Set session expiration to 5 days.
  const expiresIn = 60 * 60 * 24 * 5 * 1000;
  // Create the session cookie. This will also verify the ID token in the process.
  // The session cookie will have the same claims as the ID token.
  // To only allow session cookie setting on recent sign-in, auth_time in ID token
  // can be checked to ensure user was recently signed in before creating a session cookie.
  getAuth()
    .createSessionCookie(idToken, { expiresIn })
    .then(
      (sessionCookie) => {
        // Set cookie policy for session cookie.
        const options = { maxAge: expiresIn, httpOnly: true, secure: true };
        res.cookie('session', sessionCookie, options);
        res.end(JSON.stringify({ status: 'success' }));
      },
      (error) => {
        res.status(401).send('UNAUTHORIZED REQUEST!');
      }
    );
});

我已经实现了可调用函数,但我现在知道如何将选项附加到我的 cookie 字符串。

以下是我的代码:


// I want the return type to be a Promise of a cookie object, not a string
export const setCookie = https.onCall(async (context: https.CallableContext): Promise<string> => { 
    try {
        console.log(context);
        const auth: Auth = getAuth();
        const idToken: DecodedIdToken = await auth.verifyIdToken(context.instanceIdToken!); // https://firebase.google.com/docs/auth/admin/verify-id-tokens#web
        console.log("idToken: ", idToken);

        const cookie: string = await auth.createSessionCookie(idToken.uid, { expiresIn: 300000 });
        const options = {
            maxAge: 300000,
            httpOnly: true,
            secure: true,
            sameSite: "strict",
        };
        // res.cookie("session", cookie, options);
        return cookie; // should be assigned to __session cookie with domain .web.app
        // httpOnly=true, secure=true and sameSite=strict set.
    } catch (error) {
        console.log("ERROR FOUND: ", error);
        throw new https.HttpsError("unknown", "Error found in setCookie");
    }
});

有什么方法可以使用 Callable Firebase Cloud Function 来做到这一点? 我找到的所有文档和资源都需要 express 才能使用 Node.js 发送 cookie。

谢谢!

您链接到的文档假定您正在使用 express 编写标准的 nodejs 后端代码。 但是,您的代码使用的是可调用类型函数。 它们不一样,也没有相同的能力。 可调用函数不允许您在响应中设置 cookie。 您只能将 JSON 有效负载发送回客户端; SDK 处理所有 HTTP 标头,它们不在您的控制范围内。

也许您应该考虑使用标准的 HTTP 类型函数(onRequest),您可以在其中对响应中的标头进行一些控制。

暂无
暂无

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

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