Google 登录和后端身份验证

时间:2021-02-08 11:34:18

标签: php reactjs google-signin

我遵循了 Google Signin 的教程,它在客户端运行良好。我曾尝试导出令牌服务器端,但我不断收到 500 错误,这是在我的 config.php 文件中生成的。我已经糊涂了:/如果您能看到我正在尝试做的事情,我缺少什么?

config.php

<?php
//config.php
    session_start();
    require_once('../vendor/autoload.php');
    $google_client = new Google_Client();

    $google_client->setClientId($CLIENT_ID);
    $google_client->setClientSecret($CLIENT_SECRET);

    $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    $google_client->setRedirectUri($redirect_uri);

    $google_client->addScope('email');
    $google_client->addScope('profile');

?>

createJSON.php

<?php 
include('config.php');
  if (isset($_POST['code'])) {
      $token = $client->fetchAccessTokenWithAuthCode($_POST['code']);
    
 
    if(!isset($token['error'])){

      $google_client->setAccessToken($token['access_token']);

      $_SESSION['access_token'] = $token['access_token'] ;

      $google_service = new Google_Service_0auth2($google_client);

      $data = $google_service->userinfo->get();

      if(!empty($data[email])){
        $_SESSION['user_email'] = $data['email'];
      }

    }

  }
?>

我有下面的代码,它是成功登录时的登陆页面(我使用的是 isSignedIn={true}),它将使用 axios 启动服务器端会话,但我不知道要发送什么,甚至我不知道做对了吗?

除非遇到 config.php 文件并生成 500 错误,否则一切正常。 [从测试中更新的代码 - 现在得到 http://localhost/php/createJSON.php net::ERR_CONNECTION_REFUSED]

 const responseGoogle = response => {       
            setName(response.profileObj.name);
            setUrl(response.profileObj.imageUrl);
            const postData = { code: response.tokenId };
            // Send a POST request                  
           axios({
            method: 'POST',
            url: "http://localhost:80/php/createJSON.php",
            headers: {
              "Access-Control-Allow-Origin": "*"
            },
          //  headers: axiosConfig,
            data: postData
            })
            .then((response) => {
                console.log('RESPONSE.DATA '+response.data);
            }, (error) => {
                console.log(error);
            });

1 个答案:

答案 0 :(得分:1)

已解决:)

我遇到了一些问题:

  1. Axios POST 的路径不正确 - 只需要基本的相对路径

  2. 我的配置文件只需要供应商路径和客户端 ID 变量

  3. 我没有处理 JSON 帖子,现在我已经将代码放在 Google https://developers.google.com/identity/sign-in/web/backend-auth 上并且一切正常:)

    $CLIENT_ID]); // 指定访问后端的应用的CLIENT_ID $payload = $client->verifyIdToken($post['code']); 如果($有效载荷){ $userid = $payload['sub']; // 如果请求指定了 G Suite 域: //$domain = $payload['hd']; 回声 $payload['email']; } 别的 { // 无效的 ID 令牌 echo '失败'; } ?>