如何在Electron中为@google-cloud/speech v2配置Bearer Token
如何为Google Cloud Speech-to-Text v2的Electron客户端配置Bearer Token
问题背景
我开发了一个Electron应用,原本通过以下代码调用@google-cloud/speech v2:
const { v2 } = require('@google-cloud/speech'); ... client = new v2.SpeechClient({ apiEndpoint: `us-central1-speech.googleapis.com`, keyFilename: keyFilename, projectId: PROJECT_ID, }); ... client._streamingRecognize() ...
这个实现运行正常,但出于安全考虑(应用已打包),不能在Electron应用中存放JSON密钥文件。于是我在服务器端搭建了API,安全存储密钥并返回访问Token:
// 服务器端API const auth = new GoogleAuth({ keyFilename: speech.keyFilename, scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); const client = await auth.getClient(); const accessToken = await client.getAccessToken(); return { token: accessToken.token, };
我尝试通过authToken参数配置SpeechClient,但无法生效:
const authToken = await fetch('my-api/token'); speechClient = new v2.SpeechClient({ apiEndpoint: `us-central1-speech.googleapis.com`, // keyFilename: keyFilename, projectId: PROJECT_ID, authToken: `Bearer ${token}` });
另外,因为需要的_streamingRecognize功能没有在Google REST API文档中找到,没办法直接用REST API。请问该如何正确配置Bearer Token?
解决方案
@google-cloud/speech v2的客户端依赖google-auth-library处理认证,它并不直接支持authToken参数。你需要自定义一个认证客户端,将从服务器获取的Token注入进去:
- 导入依赖的认证客户端:
const { OAuth2Client } = require('google-auth-library'); const { v2 } = require('@google-cloud/speech');
- 获取服务器Token并初始化自定义认证客户端:
// 从服务器获取Token const tokenResponse = await fetch('my-api/token'); const { token: accessToken } = await tokenResponse.json(); // 创建OAuth2客户端并设置Token凭据 const oauth2Client = new OAuth2Client(); oauth2Client.setCredentials({ access_token: accessToken, });
- 将自定义认证客户端传入SpeechClient配置:
const speechClient = new v2.SpeechClient({ apiEndpoint: `us-central1-speech.googleapis.com`, projectId: PROJECT_ID, auth: oauth2Client, // 注入自定义认证客户端 });
- 正常调用
_streamingRecognize方法:
speechClient._streamingRecognize(...)
注意事项
- 确保服务器返回的Token包含正确的权限范围(
https://www.googleapis.com/auth/cloud-platform或更精细的https://www.googleapis.com/auth/speech),否则会触发权限不足错误。 - 需处理Token过期场景:当Token失效时,重新从服务器获取新Token并更新OAuth2客户端的凭据。
内容的提问来源于stack exchange,提问作者I am L
相关产品推荐
相关产品推荐

