PHP调用Google API获取CNAME验证令牌时遇未认证问题
PHP调用Google Site Verification API获取CNAME令牌时遇UNAUTHENTICATED错误
我在使用PHP调用Google Site Verification API获取DNS CNAME验证令牌时,始终收到UNAUTHENTICATED(401)错误。PHP版本为8.x,密钥文件路径权限正常,已尝试新建服务账号、切换OAuth2密钥配置,问题仍未解决。
代码示例
$client = new Google_Client([ 'projectId' => PROJECT_ID, 'keyFilePath' => $_SERVER['DOCUMENT_ROOT'] . KEY_FILE_PATH, ]); $client->addScope('https://www.googleapis.com/auth/siteverification'); $service = new Google_Service_SiteVerification($client); $body = new Google_Service_SiteVerification_SiteVerificationWebResourceGettokenRequest([ 'verificationMethod' => 'DNS_CNAME', 'site' => [ 'type' => 'INET_DOMAIN', 'identifier' => $CUSTOMER_DOMAIN ] ]); try { $response = $service->webResource->getToken($body); } catch (Exception $e) { var_dump($e); }
错误信息
object(Google\Service\Exception)#56 (8) { ["errors":protected]=> array(1) { [0]=> array(5) { ["message"]=> string(15) "Login Required." ["domain"]=> string(6) "global" ["reason"]=> string(8) "required" ["location"]=> string(13) "Authorization" ["locationType"]=> string(6) "header" } } ["message":protected]=> string(844) "{ "error": { "code": 401, "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.", "errors": [ { "message": "Login Required.", "domain": "global", "reason": "required", "location": "Authorization", "locationType": "header" } ], "status": "UNAUTHENTICATED", "details": [ { "@type": "type.googleapis.com/google.rpc.ErrorInfo", "reason": "CREDENTIALS_MISSING", "domain": "googleapis.com", "metadata": { "method": "security.irdb.api.VerificationService.GetToken", "service": "siteverification.googleapis.com" } } ] } }
解决方案建议
- 确认服务账号权限:Google Site Verification API需要服务账号具备对应域名的操作权限。需在Google Search Console中将服务账号邮箱添加为域名的所有者或权限用户,或者在Google Cloud IAM中为服务账号分配Site Verification Admin角色。
- 规范客户端初始化:避免混用多种凭证配置方式,推荐使用服务账号密钥文件并显式启用服务账号认证模式:
$client = new Google_Client(); // 加载服务账号密钥文件 $client->setAuthConfig($_SERVER['DOCUMENT_ROOT'] . KEY_FILE_PATH); $client->addScope('https://www.googleapis.com/auth/siteverification'); // 启用应用默认凭证(服务账号模式) $client->useApplicationDefaultCredentials(); - 检查API启用状态:登录Google Cloud控制台,确认Site Verification API已被启用,未启用的API会直接拒绝认证请求。
- 验证密钥文件类型:确保使用的是服务账号的JSON密钥(从IAM -> 服务账号 -> 密钥页面创建),而非OAuth客户端ID的密钥(两种凭证用途不同)。
- 调试请求头:添加日志查看请求是否携带有效Authorization头,确认token是否正常生成:
$client->setHttpClient(new \GuzzleHttp\Client([ 'on_stats' => function (\GuzzleHttp\TransferStats $stats) { error_log('Auth Header: ' . ($stats->getRequest()->getHeader('Authorization')[0] ?? 'Missing')); } ]));
内容的提问来源于stack exchange,提问作者tidpe
相关产品推荐
相关产品推荐

