PHP

Google Single Sign-On implementation with PHP

CK CK 3776 
Created at  
1,362 0 0

Single Sign-On (SSO) is an authentication process that allows a user to access multiple applications or systems using a single set of credentials (typically a username and password). Once authenticated, the user is granted access to all linked resources without needing to re-enter their login information for each individual application. This simplifies user experience, enhances security by reducing the number of passwords to manage, and streamlines administrative tasks for organizations.

 

To implement Google Single Sign-On (SSO) in PHP, you typically use the Google API client library. Below is a basic step-by-step guide and code example to integrate Google SSO:

 

Step 1: Set up a Google API project

  1. Go to the Google Cloud Console.
  2. Create a new project (or use an existing one).
  3. Navigate to APIs & Services > Credentials.
  4. Click Create Credentials > OAuth 2.0 Client ID.
  5. Set up the OAuth consent screen and configure your app.
  6. Under "Authorized redirect URIs," add the URL where your application will handle Google's callback, e.g., http://localhost/callback.php.


Step 2: Install the Google API Client Library

Install the PHP Google Client Library using Composer:

composer require google/apiclient:^2.0

Step 3: Implement the PHP code

Here’s a basic example:

index.php - Login page

<?php
require_once 'vendor/autoload.php';

session_start();

// Initialize Google Client
$client = new Google_Client();
$client->setClientId('YOUR_CLIENT_ID');
$client->setClientSecret('YOUR_CLIENT_SECRET');
$client->setRedirectUri('http://localhost/callback.php');
$client->addScope("email");
$client->addScope("profile");

// Generate the login URL
$login_url = $client->createAuthUrl();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Google SSO</title>
</head>
<body>
    <a href="<?= htmlspecialchars($login_url) ?>">Login with Google</a>
</body>
</html>

callback.php - Handle the Google callback

<?php
require_once 'vendor/autoload.php';

session_start();

$client = new Google_Client();
$client->setClientId('YOUR_CLIENT_ID');
$client->setClientSecret('YOUR_CLIENT_SECRET');
$client->setRedirectUri('http://localhost/callback.php');

if (isset($_GET['code'])) {
    $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
    $client->setAccessToken($token);

    // Get user information
    $google_oauth = new Google_Service_Oauth2($client);
    $google_account_info = $google_oauth->userinfo->get();

    // Save user information in session or database
    $_SESSION['user'] = [
        'id' => $google_account_info->id,
        'name' => $google_account_info->name,
        'email' => $google_account_info->email,
        'picture' => $google_account_info->picture,
    ];

    // Redirect to a logged-in page
    header('Location: profile.php');
    exit();
} else {
    echo "Failed to authenticate with Google!";
}

profile.php - Display user information

<?php
session_start();

if (!isset($_SESSION['user'])) {
    header('Location: index.php');
    exit();
}

$user = $_SESSION['user'];
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>User Profile</title>
</head>
<body>
    <h1>Welcome, <?= htmlspecialchars($user['name']) ?></h1>
    <p>Email: <?= htmlspecialchars($user['email']) ?></p>
    <img src="<?= htmlspecialchars($user['picture']) ?>" alt="Profile Picture">
    <br>
    <a href="logout.php">Logout</a>
</body>
</html>

logout.php - Logout

<?php
session_start();
session_destroy();
header('Location: index.php');
exit();

Key Notes

  1. Redirect URI: Ensure that the redirect URI in your Google Cloud Console matches the one in your setRedirectUri method.
  2. Security: Avoid hardcoding client credentials in production. Use environment variables or configuration files.
  3. HTTPS: Use HTTPS in production environments to secure the OAuth flow.
  4. Token Validation: Validate the token to prevent misuse in production applications.

This implementation allows users to log in using Google, fetch their profile information, and manage sessions accordingly.
 

Tags Google SSO Google Single Sign-On SSO Single Sign-On Facebook X
Comments 0
  1. When you Postgresql Module is not able to open connection : Doubt your libpq version
    472
  2. How to Get a YouTube Channel ID from a URL in PHP
    1,012
  3. Building a MCP server in PHP
    624
  4. PHP 7 vs PHP 8
    1,240
  5. Upgrading PHP 7.4 to PHP 8.1 in CentOS 7
    640
  6. gRPC Server with PHP
    499
  7. PHP Code to Fetch current Coinbase Assets (Balances)
    435
  8. PHP Code to Fetch PEPE coin pricing based in USD from Coinbase
    361
  9. PHP Superglobal Variables do not require additional syntax to access it
    2,607
  10. Run Python Code with Virtual Environment in PHP
    671
  11. PHP Simplified Operators
    317
  12. PHP Heredoc (aka Nowdoc)
    419
  13. PHP Post Processing by disconnecting HTTP connection and continuing the remaining logics
    1,794
  14. WordPress Remote Posting with PHP
    1,667
  15. Google BigQuery Example to converted Nested FIelds in JSON
    458
  16. Verifying Apple In-App Purchase validation receipt with PHP
    1,774
  17. Useful code for file-based Unit Test in PHP
    497
  18. Function Overloading Implementation in PHP with Magic Mathods
    1,751
  19. PHP Magic - the Null Coalescing Operator (??) - return the value if the give variable is NULL
    1,664
  20. How do I find php.ini on Mac?
    488
  21. Mastering Excel Data Importation in PHP
    553
  22. Create Blob Image in HTML based on the given Text, Width and Height in the Center of the Image without saving file
    954
  23. How do I determine the client IP type (IPv4/IPv6) in PHP
    828
Recently updated
  1. How do I create animated background for Google Meet?
    18,990
  2. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    192
  3. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    75
  4. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    150
  5. Array of arguments passed to script in PHP
    83
  6. Invalid Auction Storms in Ad Tech
    91
  7. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    194
  8. The Two Clocks of Ad Server Architecture
    61
  9. Frequency Cap Architecture Overview
    505
  10. Collecting Proof-of-Play from 100,000 Screens
    139
  11. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    276
  12. What is RedisVL?
    102
  13. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    218
  14. TPU & GPU Cluster Management Tools
    229
  15. The Concept of Scaffolding in AI Agents
    217
  16. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    568
  17. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    246
  18. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    321
  19. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    196
  20. Machine Learning: Training vs. Ranking
    200
  21. The Continuous Learning Machine: Designing a Loop That Actually Turns
    212
  22. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    188
  23. Designing a Data Curation System Around a Vector Database
    212
  24. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    228
  25. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    646
  26. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    179
  27. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    203
  28. Understanding Data Lineage
    251
  29. System Requirements and Architecture: Intelligent Priority-Based Scheduler
    159
  30. GPU & LLM Cluster Infrastructure & Task Scheduling Architecture
    229