簡體   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