Google在PHP后端和JS前端中登录

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

前端是100%JS。 用户单击登录按钮,会收到authResult['code']并通过ajax发送到localhost/api/user/login ,其内容如下:

     $code = $data['code'];
    require_once 'Google/Client.php';
    $client = new Google_Client();
    $client->setClientId('xxxxxx');
    $client->setClientSecret('xxxxx');
    $client->setRedirectUri('http://localhost:8080');
    $client->setScopes('email'); //Why do I need this? I already set scope in JS.
    $client->authenticate($code);   //It fails here. with no error. just 400 bad request.
    $token = json_decode($client->getAccessToken());
    $reqUrl = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=' .
          $token->access_token;
    $req = new Google_HttpRequest($reqUrl);
    $tokenInfo = json_decode(
      $client::getIo()->authenticatedRequest($req)->getResponseBody());

   //Check errors. 
   //Save user personal info in database
   //Set login sessions
  1. 如果已经在javascript中设置了作用域,为什么还要设置作用域?
  2. 为什么在调用authenticate函数时失败? 我没有犯错。
  3. 为什么在后端需要setRedirectUri()?
google-plus google-login
1个回答
0
投票
  1. 在这种情况下,您无需设置范围。
  2. (也请参阅答案3):检查您的客户端ID是否与Javascript中使用的ID匹配,并且客户端密码与控制台中的密码完全相同(没有尾随/前导空格)。
  3. 将您的redirecturi更改为“ postmessage”-这是通过Javascript流程生成代码时使用的字符串。

您也可以尝试手动构建网址并使用curl对其进行调用,以确保一切均符合您的预期: https : //developers.google.com/accounts/docs/OAuth2WebServer#handlingtheresponse

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