代理的Firebase函数存在跨域状态cookie问题



我使用这个例子开发了一个oAuth登录。遇到的第一个问题是,如果浏览器中禁用了第三方cookie(现在默认情况下(,则状态cookie验证。按照这个答案的建议,我代理了函数。

所以我使用Hosting重写来代理函数,这样你就在同一个域中,第一个重定向函数设置的服务器cookie似乎与应用程序在同一域中。就是这样

  1. 用户被重定向到一个云函数,该函数设置cookie并将用户重定向到第三方身份验证提供程序
  2. 用户登录
  3. 用户再次重定向到应用程序,应用程序获取授权码并将用户重定向到令牌功能
  4. token函数尝试读取状态cookie,但根本没有cookie

当我试图从令牌功能读取cookie时

[Object: null prototype] {}

这是主机重写

"hosting": {
...
"rewrites":  [
{
"source": "/redirect",
"function": "redirect"
},
{
"source": "/token**",
"function": "token"
},
{
"source": "**",
"destination": "/index.html"
}
],

这是重定向功能

exports.redirect = functions.https.onRequest((req, res) => {
cookieParser()(req, res, () => {
const redirect_uri = `https://${process.env.GCLOUD_PROJECT}.firebaseapp.com/auth.html`
const state = req.cookies.state || crypto.randomBytes(20).toString('hex')
const authorizationUri = fedidClient().authorizationCode.authorizeURL({
redirect_uri: redirect_uri,
scope: OAUTH_SCOPES,
state: state,
})
res.cookie('state', state.toString(), {
maxAge: 3600000,
secure: true,
httpOnly: true,
})
res.redirect(authorizationUri)
})
})

这是代币功能

exports.token = functions.https.onRequest((req, res) => {
const redirect_uri = `https://${process.env.GCLOUD_PROJECT}.firebaseapp.com/auth.html`  
try {
return cookieParser()(req, res, async () => {
if (!req.cookies.state) {
throw new Error(
'State cookie not set or expired. Maybe you took too long to authorize. Please try again.'
)
}
const tokenConfig = {
code: req.query.code,
redirect_uri: redirect_uri,
scope: OAUTH_SCOPES,
}
const result = await fedidClient().authorizationCode.getToken(tokenConfig)
const accessToken = fedidClient().accessToken.create(result)
let user = {}
await getUserInfo(accessToken)
.then((result) => result.json())
.then((json) => (user = json))
// Create a Firebase account and get the Custom Auth Token.
const firebaseToken = await createFirebaseAccount(
user.uid,
user.displayName,
user.mail,
accessToken.token.access_token
)
res.jsonp({
token: firebaseToken,
})
})
} catch (error) {
return res.status(500).jsonp({ error: error.toString })
}
})    

为什么cookie没有通过第二个云功能?如果禁用了重写并启用了第三方cookie,则代码可以正常工作。

您可能无意中发现了Firebase Hosting中的缓存功能,该功能会剥离除__session之外的所有cookie。

将Firebase主机与云功能或云一起使用时运行时,cookie通常会从传入请求中剥离。这是这对于允许有效的CDN缓存行为是必要的。只有允许特殊命名的__session cookie传递到执行您的应用程序。

尝试将您的cookie重命名为__session,看看是否能修复它。

最新更新