简体   繁体   English

Firebase Google 登录令牌过期问题

[英]Firebase Google Sign-In token expiration issue

I want to let my users send emails in my app through their Gmail account.我想让我的用户通过他们的 Gmail 帐户在我的应用程序中发送电子邮件。 So, in my front-end, I'm collecting the token generated with所以,在我的前端,我正在收集生成的令牌

const provider = new firebase.auth.GoogleAuthProvider()
provider.addScope('https://www.googleapis.com/auth/gmail.send')
provider.setCustomParameters({
    access_type: 'offline',
    prompt: 'consent',
})
firebase.auth()
  .signInWithPopup(provider)
  .then((result) => {
    var credential = result.credential;
    var token = credential.accessToken;
  })

In my backend, I'm using this token to send emails on their behalf thanks to the Google API.在我的后端,感谢 Google API,我正在使用此令牌代表他们发送电子邮件。 Eveything works well but the token only last one hour...一切运作良好,但令牌只能持续一小时......

Do you have any recommandations about the right way to handle this?您对处理此问题的正确方法有任何建议吗? Do I need to extend the duration of the token?我需要延长令牌的期限吗? Do I have to create a new token every time I want to send an email?每次我想发送 email 时都必须创建一个新令牌吗? Or do I have to not use firebase to collect the token?还是我必须不使用 firebase 来收集令牌?

By default, Firebase auth returns a short-lived authentication token and a refresh token that you can use to extend that session indefinitely.默认情况下,Firebase auth 返回一个短暂的身份验证令牌和一个刷新令牌,您可以使用它来无限期地扩展该 session。 In order to extend that session you'll need to implement session cookies .为了扩展 session 您需要实现 session cookies

Here's a brief summary of how it works:以下是其工作原理的简要总结:

  1. User signs in using .signInWithPopup()用户使用.signInWithPopup()

  2. User POSTs that ID token to a backend API endpoint that calls .verifyIdToken() to validate the token and then .createSessionCookie() with whatever expiration you desire.用户将该 ID 令牌发布到后端 API 端点,该端点调用.verifyIdToken()来验证令牌,然后.createSessionCookie()使用您想要的任何到期时间。

  3. Backend reponds with a set-cookie HTTP parameter containing the generated session cookie.后端使用包含生成的 session cookie 的set-cookie HTTP 参数进行响应。

Here's an example of what that backend API endpoint would look like:这是后端 API 端点的示例:

  login(req: any, res: Response) {
    // Cookie has a 30 day expiration
    const AUTH_COOKIE_LENGTH = 30;
    
    // If no ID Token was passed, return an error
    if (!req.body.idToken) {
      return res.status(400).end();
    }

    // The ID Token passed as a POST parameter
    const idToken = req.body.idToken.toString().trim();
    
    // Verify the ID Token
    admin.auth().verifyIdToken(idToken)
      .then(async (user) => {
        // Cookie expires 
        const expiresIn = 60 * 60 * 24 * AUTH_COOKIE_LENGTH * 1000;

        // Generate the session cookie
        admin.auth().createSessionCookie(idToken, {expiresIn})
          .then((sessionCookie) => {
            // Add the set-cookie parameter to the response
            res.cookie("__session", sessionCookie, {
              domain: '.example.com',
              secure: true,
              sameSite: 'strict',
              expires: expiresIn
            });

            res.json({
              success: true
            }).end();
          }, (error: any) => {
            res.status(503).json({success: false}).end();
          });
      }).catch((error: any) => {
        res.status(401).json({success: false, error: "INVALID_TOKEN"}).end();
    });
  }

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

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