Вход с помощью Google Oauth в PHP без разрешения аутентификации - PullRequest
0 голосов
/ 14 января 2020

Я использую https://github.com/googleapis/google-api-php-client/releases

Исходный файл: https://github.com/googleapis/google-api-php-client/archive/v2.4.0.zip

для получения таких данных пользователя, как Username, email, profile picture, user ID, access token, refresh token so on, и я смог чтобы получить все данные с разрешением пользователя на аутентификацию и сохранить его в моей базе данных.

Google_config. php

require_once 'Google/autoload.php';
//require_once 'client.json';

session_start();

$client = new Google_Client();
$client->setApplicationName("Login with Google Account");

$client->setClientId('xxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com');
$client->setClientSecret('xxxxxxxxxxxxxxxxxxxxx');
$client->setRedirectUri('http://localhost:8000/ads/login/redirect.php');

//$client->setAuthConfig("client.json");

$client->addScope([
    "https://www.googleapis.com/auth/userinfo.email",
    "https://www.googleapis.com/auth/userinfo.profile"
]);
$client->setAccessType('offline');
$client->setApprovalPrompt ("force");

Redirect. php

if (isset($_SESSION['accessToken'])) {
    $client->setAccessToken($_SESSION['accessToken']);
} else if (isset($_GET['code'])) {
    $client->authenticate($_GET['code']);
    $access_token = $client->getAccessToken();
    $_SESSION['accessToken'] = $access_token;
} else {
    header('location : index.php');
}

$oauth = new Google_Service_Oauth2($client);


if ($client->getAccessToken()) {
    // Get user profile data from google
    $gpUserProfile = $oauth->userinfo->get();

    // Initialize User class
    $user = new User();

    // Getting user profile info
    $gpUserData = array();
    $gpUserData['oauth_uid'] = !empty($gpUserProfile['id']) ? $gpUserProfile['id'] : '';
    $gpUserData['first_name'] = !empty($gpUserProfile['given_name']) ? $gpUserProfile['given_name'] : '';
    $gpUserData['last_name'] = !empty($gpUserProfile['family_name']) ? $gpUserProfile['family_name'] : '';
    $gpUserData['email'] = !empty($gpUserProfile['email']) ? $gpUserProfile['email'] : '';
    $gpUserData['gender'] = !empty($gpUserProfile['gender']) ? $gpUserProfile['gender'] : '';
    $gpUserData['locale'] = !empty($gpUserProfile['locale']) ? $gpUserProfile['locale'] : '';
    $gpUserData['picture'] = !empty($gpUserProfile['picture']) ? $gpUserProfile['picture'] : '';
    $gpUserData['link'] = !empty($gpUserProfile['link']) ? $gpUserProfile['link'] : '';

    // Insert or update user data to the database
    $gpUserData['oauth_provider'] = 'google';
    $userData = $user->checkUser($gpUserData);

    // Storing user data in the session
    $_SESSION['userData'] = $userData;

    // Render user profile data
    if (!empty($userData)) {
        $output = '<h2>Google Account Details</h2>';
        $output .= '<div class="ac-data">';
        $output .= '<img src="' . $userData['picture'] . '">';
        $output .= '<p><b>Google ID:</b> ' . $userData['picture'] . '</p>';
        $output .= '<p><b>Google ID:</b> ' . $userData['oauth_uid'] . '</p>';
        $output .= '<p><b>Name:</b> ' . $userData['first_name'] . ' ' . $userData['last_name'] . '</p>';
        $output .= '<p><b>Email:</b> ' . $userData['email'] . '</p>';
        $output .= '<p><b>Gender:</b> ' . $userData['gender'] . '</p>';
        $output .= '<p><b>Locale:</b> ' . $userData['locale'] . '</p>';
        $output .= '<p><b>access token:</b> ' . $client->getAccessToken() . '</p>';
        $output .= '<p><a href="' . $userData['link'] . '" target="_blank">Click to visit Google+</a></p>';
        $output .= '<p>Logout from <a href="logout.php">Google</a></p>';
        $output .= '</div>';
    } else {
        $output = '<h3 style="color:red">Some problem occurred, please try again.</h3>';
    }
} else {
    // Get login url
    $authUrl = $client->createAuthUrl();

    // Render google login button
    $output = '<a href="' . filter_var($authUrl, FILTER_SANITIZE_URL) . '"><img src="images/google-sign-in-btn.png" alt=""/></a>';
}
?>
<div class="container">
    <!-- Display login button / Google profile information -->
    <?php echo $output; ?>
</div>

Теперь моя проблема КАК РАБОТАЕТ GOOGLE LOGIN Потому что, когда я использую описанный выше метод, он получает аутентификацию , а затем возвращает информацию о пользователе.

Где здесь, в { ссылка }, когда я пытаюсь войти в систему, я смог войти в систему с учетной записью Google с некоторым перенаправлением.

Как мне войти, попытался многие онлайн-решения и документ Google тоже.

Любое решение будет полезным.

1 Ответ

0 голосов
/ 28 января 2020

наконец простое решение здесь:

if (isset($_GET['code'])) {
try {
    $gapi = new GoogleLoginApi();
    // Get the access token 
    $data = $gapi->GetAccessToken(CLIENT_ID, CLIENT_REDIRECT_URL, CLIENT_SECRET, $_GET['code']);
    // Get user information
    $user_info = $gapi->GetUserProfileInfo($data['access_token']);
} catch (Exception $e) {
    echo $e->getMessage();
    exit();
}
}


class GoogleLoginApi {

public function GetAccessToken($client_id, $redirect_uri, $client_secret, $code) {
    $url = 'https://www.googleapis.com/oauth2/v4/token';

    $curlPost = 'client_id=' . $client_id . '&redirect_uri=' . $redirect_uri . '&client_secret=' . $client_secret . '&code=' . $code . '&grant_type=authorization_code';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
    $data = json_decode(curl_exec($ch), true);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($http_code != 200) {
        throw new Exception('Error : Failed to receieve access token');
    }
    return $data;
}

public function GetUserProfileInfo($access_token) {
    $url = 'https://www.googleapis.com/oauth2/v2/userinfo?fields=name,email,gender,id,picture,verified_email';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $access_token));
    $data = json_decode(curl_exec($ch), true);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($http_code != 200) {
        throw new Exception('Error : Failed to get user information');
    }
    return $data;
}

}
...