您不应在后端身份验证用户(尽管可能是可能的),因为它可能会带来意外的后果,但是您可以在浏览器上使用
signInWithEmailAndPassword
来验证用户,然后将“ ID令牌”验证到后端。
frontend(使用
firebase
):
后端(使用
firebase-admin
const decodedToken = await getAuth(app).verifyIdToken(body.idToken)
//check decodedToken.uid equals body.uid
您可以在此处阅读更多“ ID令牌验证”:
我曾经有一段时间以前遇到了同样的问题。我有遗产代码需要迁移到必须向后兼容的新API。我相信旧的Firebase模块(版本8)上有SignWitheMailandPassword方法,但最近的版本却没有。我不得不使用Identity平台RESTAPI
async function loginUserWithEmailAndPassword(email: string, password: string) {
const apiKey = 'your-firebase-api-key'; //This is required to identify your project
const url = `https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=${apiKey}`;
try {
const { data } = await axios.post(url, {
email,
password,
returnSecureToken: true,
});
return data
} catch (e) {
if (axios.isAxiosError(e)) {
if (e.response?.data) {
const errorData = e.response.data as { error: { message: string } };
this.logger
.withFields(errorData)
.warn('Failed to sign in with email and password');
throw new BadRequestException(errorData.error.message || 'Failed to sign');
}
}
this.logger.withException(e).warn('Failed to sign in with custom token');
throw e;
}
}