如何从Firebase获得对开发有效的idToken,而不必增加前端? [英] How to get an idToken that is valid for development from firebase without having to spin up my frontend?
问题描述
我正在处理一些Firebase功能.这将检查用户是否首先在Firebase中登录.但是,这在开发中有点麻烦.现在,我需要先登录前端以获得 id_token
,并将其传递给我的函数url,然后查看结果.
I am working on some firebase functions. This one will check if an user is logged in in firebase first. However this is a bit of a hassle in development. Now I need to login on the frontend first to get the id_token
, pass it to my function url, then see the result.
我正在遵循的过程在官方文档中有所描述: https://firebase.google.com/docs/auth/admin/verify-id-tokens
The process I am following is described in the official docs: https://firebase.google.com/docs/auth/admin/verify-id-tokens
node.js
const admin = require('firebase-admin');
admin.initializeApp();
module.exports = function( request, response ) {
if( !request.query.id_token )
response.status(400).json({message: 'id token has not been provided'});
admin.auth()
.verifyIdToken( request.query.id_token )
.then( token => {
// TODO: redirect to payment portal
return response.status(200).json({message: 'Success'});
})
.catch( error => {
return response.status(401).json({message: 'You are currently not logged in as an authorised user'});
})
}
是否有一种方法可以从Firebase中获取有效的 id_token
,而不必提高前端速度?也欢迎使用简便的替代解决方案.
Is there a way to get an id_token
that is valid from firebase without having to spin up my frontend? Good and simple alternatives solutions are welcome too.
注意:我在开发过程中使用的是Firebase模拟器.
NOTE: I am using the firebase emulators during development.
推荐答案
由于您使用的是Firebase模拟器,因此您可能会创建伪造的用户并以编程方式检索id令牌.下面的代码创建并登录用户,并返回一个id_token,它将被您的函数接受.
Since you're using the Firebase emulators you may create a fake user and retrieve an id token programmatically. The code below creates and logs in a user and returns an id_token that will be accepted by your function.
var firebase = require("firebase/app");
require("firebase/auth");
// Initialize Firebase and connect to the Authentication emulator
var firebaseConfig = {
// Insert Firebase config here
};
firebase.initializeApp(firebaseConfig);
firebase.auth().useEmulator('http://localhost:9099/');
// Create a fake user and get the token
firebase.auth().createUserWithEmailAndPassword("example@example.com", "password")
.then((userCredential) => {
console.log("User created")
});
firebase.auth().signInWithEmailAndPassword("example@example.com", "password")
.then((userCredential) => {
console.log("User logged in")
userCredential.user.getIdToken().then((idToken) => {
console.log(idToken)
});
});
这篇关于如何从Firebase获得对开发有效的idToken,而不必增加前端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!