[英]Firebase Google Sign-In token expiration issue
我想讓我的用戶通過他們的 Gmail 帳戶在我的應用程序中發送電子郵件。 所以,在我的前端,我正在收集生成的令牌
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;
})
在我的后端,感謝 Google API,我正在使用此令牌代表他們發送電子郵件。 一切運作良好,但令牌只能持續一小時......
您對處理此問題的正確方法有任何建議嗎? 我需要延長令牌的期限嗎? 每次我想發送 email 時都必須創建一個新令牌嗎? 還是我必須不使用 firebase 來收集令牌?
默認情況下,Firebase auth 返回一個短暫的身份驗證令牌和一個刷新令牌,您可以使用它來無限期地擴展該 session。 為了擴展 session 您需要實現 session cookies 。
以下是其工作原理的簡要總結:
用戶使用.signInWithPopup()
用戶將該 ID 令牌發布到后端 API 端點,該端點調用.verifyIdToken()
來驗證令牌,然后.createSessionCookie()
使用您想要的任何到期時間。
后端使用包含生成的 session cookie 的set-cookie
HTTP 參數進行響應。
這是后端 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.