Skip to content

Instantly share code, notes, and snippets.

@muathendirangu
Created March 3, 2024 21:04
Show Gist options
  • Save muathendirangu/278c36067964e2ee7c97822e5e37d15f to your computer and use it in GitHub Desktop.
Save muathendirangu/278c36067964e2ee7c97822e5e37d15f to your computer and use it in GitHub Desktop.
access control php script using ouath library
Leverage guzzlehttp that abstracts a lot of oauth functionality
```bash
composer require guzzlehttp/guzzle
```
Now, let's create the PHP script (`oauth_example.php`):
```php
<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
// OAuth 2.0 Authorization Server Details
$authorizationEndpoint = 'https://example.com/oauth2/authorize';
$tokenEndpoint = 'https://example.com/oauth2/token';
$clientId = 'your_client_id';
$clientSecret = 'your_client_secret';
$redirectUri = 'https://your_redirect_uri';
// API Endpoint to retrieve data
$apiEndpoint = 'https://api.example.com/data';
// Start the OAuth 2.0 authorization process
if (!isset($_GET['code'])) {
// Step 1: Redirect the user to the authorization endpoint
$authorizationUrl = $authorizationEndpoint . '?' . http_build_query([
'client_id' => $clientId,
'redirect_uri' => $redirectUri,
'response_type' => 'code',
'scope' => 'read', // Adjust scope as needed
]);
header('Location: ' . $authorizationUrl);
exit;
} else {
// Step 2: Exchange the authorization code for an access token
$authCode = $_GET['code'];
$client = new Client();
try {
$response = $client->post($tokenEndpoint, [
'form_params' => [
'grant_type' => 'authorization_code',
'code' => $authCode,
'client_id' => $clientId,
'client_secret' => $clientSecret,
'redirect_uri' => $redirectUri,
],
]);
$tokenData = json_decode($response->getBody(), true);
// Step 3: Use the access token to make authenticated requests to the API
$accessToken = $tokenData['access_token'];
// Make a request to the API using the access token
$apiResponse = $client->get($apiEndpoint, [
'headers' => [
'Authorization' => 'Bearer ' . $accessToken,
'Accept' => 'application/json',
],
]);
$apiData = json_decode($apiResponse->getBody(), true);
// Display the API data
echo "API Data:\n";
print_r($apiData);
} catch (RequestException $e) {
// Handle errors
echo 'Error: ' . $e->getMessage();
}
}
```
This script follows the OAuth 2.0 authorization code flow:
1. Redirect the user to the authorization endpoint.
2. After the user grants permission, they are redirected back to your script with an authorization code.
3. Exchange the authorization code for an access token using the token endpoint.
4. Use the obtained access token to make authenticated requests to the API.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment