从 Google Api 请求用户电子邮件返回未经授权的 401 错误

问题描述 投票:0回答:3

我尝试连接到 google API,它返回:

failed to open stream: HTTP request failed! HTTP/1.0 401 Unauthorized
我请求访问令牌,它返回了我 xxx,之后我通过以下 PHP 代码连接到 Google API:

$opts = array('http' =>
        array(
        'method'  => 'GET',
        'header' => "Authorization: OAuth $access_token\r\nContent-Type: application/json\r\n",
        )
    );
    $context = stream_context_create($opts);
    $result = file_get_contents('https://www.googleapis.com/userinfo/email?alt=json',false,$context);

哪里有错误,是我写错了标题,还是其他什么? 更新: $access_token 是我通过请求以 json 形式获得的值。

php http-headers file-get-contents oauth-2.0
3个回答
0
投票
  • 您不需要 GET 请求的内容类型标头。
  • 您需要查询此 URL 来获取用户信息:https://www.googleapis.com/oauth2/v2/userinfo
  • 确保
    $access_token
    值包含正确授权的访问令牌,因为您需要用户经历 OAUth 2.0 流程。

所有这些都记录在那里:https://developers.google.com/accounts/docs/OAuth2Login


0
投票

检查如何在 php 中执行此操作,但是当将您的客户端登录到 Google 时,您必须设置 RequestPermission 参数,以便您可以从用户的个人资料中获取信息

请求权限:'https://www.googleapis.com/auth/userinfo.profile'


0
投票

我使用 Angular(类型脚本)使用类似的方法,并在控制台上遇到“GET https://www.googleapis.com/oauth2/v3/userinfo 401(未经授权)”错误,我不知道是什么这里错误的是访问令牌是正确的并且令牌尚未过期!

私有 userInfoUrl = 'https://www.googleapis.com/oauth2/v3/userinfo';

getUserInfo(accessToken: string): Observable { const headers = new HttpHeaders().set('授权',

Bearer ${accessToken}
); 返回 this.http.get(this.userInfoUrl, { headers }); }

© www.soinside.com 2019 - 2024. All rights reserved.