PHP code example of tflori / oauth2

1. Go to this page and download the library: Download tflori/oauth2 library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

tflori / oauth2 example snippets




$handler = new Oauth2\Handler(new Oauth2\Tests\Fake\Storage());
$client = new Oauth2\Client(1, '~^https://www\.example\.com~', 'my-long-secret');
$user = new Oauth2\User();
$user->permit($client, ['basic']);

$result = $handler->getAuthToken($_SESSION['oauthId'], $client, $user, $_GET['redirect_uri']);
if ($result['status'] == OAuth2\Handler::STATUS_GRANTED) {
    header('Location: ' . $result['redirectUri']);
}



$handler = new Oauth2\Handler(new Oauth2\Tests\Fake\Storage());

$result = $handler->getAccessToken($_GET['client_id'], $_GET['client_secret'], $_GET['code']);
header('Content-Type: application/json');
echo json_encode($result);



$handler = new Oauth2\Handler(new Oauth2\Tests\Fake\Storage());

$accessToken = substr($_SERVER['HTTP_AUTHORIZATION'], strrpos($_SERVER['HTTP_AUTHORIZATION'], ' '));
if ($handler->isAuthorized($accessToken, 'this-resource')) {
    $user = $handler->getUser($accessToken);
    // request the resource and send him data
} else {
    header('HTTP/1.1 403 Forbidden');
}



$accessToken = substr($_SERVER['HTTP_AUTHORIZATION'], strrpos($_SERVER['HTTP_AUTHORIZATION'], ' '));
$result = json_decode(file_get_contents(
    'https://auth.example.com/validate.php?access_token=' . $accessToken . '&scope=this-resource'
));



$handler = new Oauth2\Handler(new Oauth2\Tests\Fake\Storage());

header('Content-Type: application/json');
if (!$handler->isAuthorized($_GET['access_token'], $_GET['scope'])) {
    echo json_encode(false); // or echo 'false';
} else {
    echo json_encode($handler->getUser($_GET['access_token']));
}



$handler = new Oauth2\Handler(new Oauth2\Tests\Fake\Storage());
$handler->destroySession($_SESSION['oauthId']);