π 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