能否获取永不过期的Firebase Auth模拟器ID令牌?
在Firebase Auth模拟器中生成ID令牌,无需前端UI测试后端
核心思路
直接通过Firebase Auth模拟器的API或Admin SDK创建测试用户并生成ID令牌,跳过前端UI步骤,方便在Postman中复用不同用户类型的令牌。
步骤1:启动Firebase Auth模拟器
确保已安装Firebase CLI,执行命令启动Auth模拟器:
firebase emulators:start --only auth
模拟器默认运行在localhost:9099。
步骤2:生成ID令牌的两种方式
方式一:用Node.js脚本(推荐,支持自定义用户声明)
- 初始化Admin SDK并指向模拟器:
const admin = require('firebase-admin'); const fetch = require('node-fetch'); admin.initializeApp({ credential: admin.credential.applicationDefault(), auth: { apiKey: "你的项目API_KEY", projectId: "你的项目ID", emulatorHost: "localhost:9099", emulatorPort: 9099 } });
- 编写脚本创建用户并生成ID令牌:
async function generateUserToken(email, password, userType) { // 创建测试用户 const user = await admin.auth().createUser({ email, password, displayName: userType }); // 生成自定义令牌(可附加用户类型等自定义声明) const customToken = await admin.auth().createCustomToken(user.uid, { userType }); // 调用模拟器API交换成ID令牌 const res = await fetch('http://localhost:9099/identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=你的项目API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: customToken, returnSecureToken: true }) }); const data = await res.json(); console.log(`[${userType}] ID令牌:`, data.idToken); console.log(`有效期: ${data.expiresIn}秒\n`); return data.idToken; } // 生成不同类型用户的令牌 generateUserToken('regular@test.com', '123456', '普通用户'); generateUserToken('admin@test.com', 'admin123', '管理员');
运行脚本后,控制台会输出不同用户的ID令牌,直接复制到Postman使用。
方式二:直接用Postman调用REST API
创建用户并获取令牌:
- 请求方法:POST
- URL:
http://localhost:9099/identitytoolkit.googleapis.com/v1/accounts:signUp?key=你的项目API_KEY - 请求体(JSON):
{ "email": "guest@test.com", "password": "guest123", "returnSecureToken": true } - 响应中
idToken即为可用的身份令牌。
已有用户登录获取令牌:
- 请求方法:POST
- URL:
http://localhost:9099/identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=你的项目API_KEY - 请求体(JSON):
{ "email": "guest@test.com", "password": "guest123", "returnSecureToken": true }
步骤3:复用令牌
把生成的不同用户类型令牌保存到Postman的环境变量中(比如regular_token、admin_token),后续测试接口时直接用{{regular_token}}引用,无需重复生成。
注意:模拟器重启后所有测试用户会被清空,需重新运行脚本或API调用生成新用户和令牌。
内容的提问来源于stack exchange,提问作者Rafael Zasas
相关产品推荐
相关产品推荐

