初学者咨询:Actions on Google中使用Firebase Authentication的方法及代码示例
关于Actions on Google中Firebase Authentication与Account Linking的问题解答
作为同样在Actions on Google和Firebase生态里摸爬滚打过的开发者,我来给你理清楚这个问题:
核心问题:是否需要Account Linking?
答案是肯定的——如果你需要在应用中关联用户的Firebase持久化身份,就必须使用Account Linking。原因很简单:Actions on Google本身给你的用户标识(比如user.id)是会话级或临时的,无法直接关联到Firebase Auth中的用户账号。只有通过Account Linking,才能把Actions的用户和Firebase的持久用户绑定起来,实现用户数据的跨会话保存、个性化服务等功能。
具体操作步骤
1. 配置Firebase Authentication
- 登录Firebase控制台,创建/打开你的项目
- 进入「Authentication」->「登录方法」,启用你需要的登录提供商(比如Google、邮箱/密码)
- 前往「项目设置」->「应用」,添加一个Web应用,获取你的Firebase配置(包含
apiKey、authDomain等信息) - 打开关联的Google Cloud控制台(Firebase项目默认绑定GCP项目),进入「API和服务」->「凭据」,创建一个OAuth客户端ID:
- 应用类型选择「Web应用」
- 在「授权重定向URI」中添加Actions on Google提供的回调地址(你在Actions Console配置Account Linking时会看到这个地址,格式类似
https://oauth-redirect.googleusercontent.com/r/[你的项目ID])
2. 在Actions Console设置Account Linking
- 打开Actions Console,进入你的项目
- 左侧菜单选择「Account Linking」
- 选择「Yes, allow users to sign into my app」,点击「Next」
- 授权类型选择「Authorization Code」,点击「Next」
- 填写以下信息:
- 客户端ID:你在GCP控制台创建的OAuth客户端ID
- 客户端密钥:对应OAuth客户端的密钥
- 授权端点:
https://accounts.google.com/o/oauth2/v2/auth(如果用Google作为登录提供商) - 令牌端点:
https://oauth2.googleapis.com/token - 范围:填写
openid email profile(根据你的需求调整,至少需要openid来获取ID令牌)
- 完成后续设置,保存配置
3. 在代码中实现账户链接与Firebase Auth验证
下面是一个基于Firebase Functions和Actions SDK的index.js示例代码,包含触发链接、验证令牌并获取Firebase用户的逻辑:
const { conversation, Simple } = require('actions-on-google'); const admin = require('firebase-admin'); // 初始化Firebase Admin(Firebase Functions环境下无需额外密钥配置) admin.initializeApp(); const auth = admin.auth(); const app = conversation({ debug: true }); // 触发账户链接的意图 app.intent('要求登录', async (conv) => { // 检查用户是否已完成账户链接 if (!conv.user.profile?.email) { // 触发Account Linking流程 conv.ask(new Simple({ speech: '请先登录你的账号,我才能为你提供个性化服务', text: '请登录你的账号' })); conv.ask(new conv.SignIn()); } else { conv.ask(`欢迎回来,${conv.user.profile.email}!`); } }); // 处理登录完成后的逻辑 app.intent('登录完成', async (conv, params, signin) => { if (signin.status === 'OK') { try { // 获取并验证用户的ID令牌 const idToken = conv.user.idToken; const decodedToken = await auth.verifyIdToken(idToken); // 获取对应的Firebase用户信息 const firebaseUser = await auth.getUser(decodedToken.uid); conv.ask(`登录成功!你的Firebase用户ID是${firebaseUser.uid}`); // 这里可以扩展逻辑,比如读取/写入Firestore中的用户数据 } catch (error) { console.error('令牌验证失败:', error); conv.ask('登录验证出现问题,请稍后重试'); } } else { conv.ask('登录未完成,如果你需要个性化服务,请重新尝试登录'); } }); exports.actions = app;
一些额外提示
- 如果使用邮箱/密码等非Google登录提供商,需要自定义授权和令牌端点,或借助Firebase Auth的REST API完成身份验证流程
- 测试时可以用Actions Console的「测试」面板,或Google Assistant模拟器来完整走一遍账户链接流程
- 若需要处理用户退出登录,可以在代码中调用
conv.signOut()触发解绑逻辑
内容的提问来源于stack exchange,提问作者mak




