升级至SpeechClient v1时遭遇OAuth2认证失败问题求助
Google Cloud Speech V1 客户端认证失败问题
我们项目原本使用google/cloud包中的SpeechClient,现在升级到未弃用的Google\Cloud\Speech\V1\SpeechClient时,触发了如下认证错误:
Google\ApiCore\ApiException: {
"message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential.",
"code": 16,
"status": "UNAUTHENTICATED",
"details": []
}
这套认证信息在旧版SpeechClient和StorageClient中都能正常使用,但升级后按新方式配置认证一直失败,需要帮忙排查。
旧版本配置(正常工作)
// $auth是数组格式的服务账号密钥文件,字段符合官方要求 $auth = [ "type" => "service_account", "project_id" => "<project_id>", "private_key_id" => "<private_key_id>", "private_key" => "-----BEGIN PRIVATE KEY-----\n<key>\n-----END PRIVATE KEY-----", "client_email" => "<xxx@xxx.gserviceaccount.com>", "client_id" => "<client_id>", "auth_uri" => "https://accounts.google.com/o/oauth2/auth", "token_uri" => "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url" => "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url" => "https://www.googleapis.com/robot/v1/metadata/x/<xxx>.gserviceaccount.com", ]; $speech = new Google\Cloud\Speech\SpeechClient([ 'keyFile' => $auth, ]); // 相同的认证信息用于StorageClient,正常工作 $storage = new Google\Cloud\Storage\StorageClient([ 'keyFile' => $auth ]);
升级后配置(触发错误)
// $auth和上面完全一致 $creds = CredentialsWrapper::build([ 'keyFile' => $auth ]); // 创建V1版本的SpeechClient $speech = new Google\Cloud\Speech\V1\SpeechClient([ 'credentials' => $creds, ]); // StorageClient仍用旧配置,正常工作 $storage = new Google\Cloud\Storage\StorageClient([ 'keyFile' => $auth ]); // ... $operation = $speech->longRunningRecognize( $config, $audio ); // 这一步能正常获取操作名称 $operation->getName(); // 这一步抛出上面的认证错误 $operation->reload();
解决方案
- 直接传递keyFile给V1客户端
V1版本的SpeechClient同样支持直接接收keyFile参数,无需手动构建CredentialsWrapper,复用已验证的认证逻辑即可:
$speech = new Google\Cloud\Speech\V1\SpeechClient([ 'keyFile' => $auth, ]);
- 检查CredentialsWrapper的正确用法
如果一定要手动构建凭证,确保使用正确的命名空间与构建逻辑:
use Google\ApiCore\CredentialsWrapper; use Google\Auth\Credentials\ServiceAccountCredentials; $credentials = new ServiceAccountCredentials( 'https://www.googleapis.com/auth/cloud-platform', $auth ); $creds = new CredentialsWrapper($credentials); $speech = new Google\Cloud\Speech\V1\SpeechClient([ 'credentials' => $creds, ]);
- 验证依赖版本兼容性
检查google/cloud-speech、google/api-core等依赖包的版本是否匹配,版本不兼容可能导致凭证处理逻辑异常,可执行composer update更新到稳定兼容版本。
内容的提问来源于stack exchange,提问作者Randommm
相关产品推荐
相关产品推荐

