Monday, 20 April 2026

#2 SSO

Advanced SSO using OAuth 2.0 (PHP)

πŸ” Advanced SSO using OAuth 2.0 with PHP

πŸ“˜ What is OAuth 2.0?

OAuth 2.0 is a secure authorization framework that allows users to login using external providers like Google without sharing passwords.

⚙️ OAuth Flow

User → Redirect to Provider → Login → Authorization Code → Token → User Info → Login

πŸ“¦ Install Google Client Library

composer require google/apiclient

πŸ”‘ Step 1: Create OAuth Client

  • Go to Google Cloud Console
  • Create project
  • Enable OAuth
  • Get Client ID & Secret

πŸ’» Step 2: Login Redirect Code

<?php
require 'vendor/autoload.php';
$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");

echo "<a href='".$client->createAuthUrl()."'>Login with Google</a>";

πŸ”„ Step 3: Callback Handling

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

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

$oauth = new Google_Service_Oauth2($client);
$user = $oauth->userinfo->get();

echo "Welcome ".$user->email;

πŸ”— Step 4: WordPress Integration

After login, pass user email to WordPress and auto-login using custom plugin.

πŸ”’ Security Features

  • Token-based authentication
  • No password sharing
  • Secure redirect
  • Access control via scopes

πŸŽ“ MCQs

  • OAuth is used for authorization
  • Access token is temporary
  • Client ID identifies application

No comments:

Post a Comment

#2 SSO

Advanced SSO using OAuth 2.0 (PHP) πŸ” Advanced SSO using OAuth 2.0 with PHP πŸ“˜ What is OAuth 2.0? OAuth 2.0 is a secure autho...