如何在Firebase云函数中将signInWithEmailAndPassword()正确转换为createCustomToken()-Node js

时间:2020-05-28 20:23:34

标签: javascript node.js firebase firebase-authentication google-cloud-functions

我想延长应用程序中用户令牌的默认到期时间。目前,我使用signInWithEmailAndPassword函数,令牌持续一个小时。

我知道可以使用createcustomtoken函数完成此操作,但是我对如何执行此操作感到有些困惑。

这是我当前的登录功能:

exports.login = (req, res) => {
    const user = {
        email: req.body.email,
        password: req.body.password
    };

    firebase.auth().signInWithEmailAndPassword(user.email, user.password)
    .then((data) => {
        return data.user.getIdToken();
    })
    .then((token) => {
        return res.json({ token });
    })
    .catch((err) => {
        console.error(err);
            return res.status(403).json({ general: "Wrong credentials, please try again"})
    })
}

1 个答案:

答案 0 :(得分:1)

不幸的是,到期时间不能超过问题(iat)超过3600秒。

在此文档中,您可以看到exp明确表示:

最多可以比iat晚3600秒。

custom token doc

但是,您可以使用没有到期时间的刷新令牌来获取新令牌。

Refresh token

如果您仍要创建自定义令牌,则可以执行以下操作:

const someJwt = jwtDecode<{ sub: string; email: string }>(someOtherTokenFromThirdParty)

// sub is the unique id for the apple user
const customToken = await admin.auth().createCustomToken(someJwt.sub, {
    ...extraClaims
})