PHP code example of plai2010 / php-oauth2

1. Go to this page and download the library: Download plai2010/php-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/ */

    

plai2010 / php-oauth2 example snippets



return [
	'provider' => [
		// As registered with the OAuth2 provider.
		'client_id' => '11111111-2222-3333-4444-567890abcdef',
		'client_secret' => 'v8rstf8eVD5My89xDOTw8CoKG6rIw9dukIjHYzPU',
		'redirect_uri' => 'http://localhost/example',

		// These items are OAuth2 provider specific.
		// The values here are for Microsoft OAuth2.
		'scope_separator' => ' ',
		'url_access_token' => 'https://login.microsoftonline.com/common/oauth2/v2.0/token',
		'url_authorize' => 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize',

		// Other options.
		'pkce_method' => 'S256',
		'timeout' => 30,
	]
];

php > config = me 'outlook_smtp' does not matter in this example.
php > $oauth2 = new PL2010\OAuth2\OAuth2Provider('outlook_smtp', $config);
php > // Scope is OAuth2 provider specific.
php > // The value here is for Outlook SMTP login authorization by
php > // Microsoft OAuth2; offline_access to request refresh token.
php > $scope = [ 'https://outlook.office.com/SMTP.Send', 'offline_access' ];
php > $url = $oauth2->authorize('code', $scope);
php > echo $url, PHP_EOL;

php > // Get from browser the URL of the 'not found' page.
php > $redir = 'http://localhost/example?code=...&state=...';
php > $token = $oauth2->receive($redir);
php > echo json_encode($token, JSON_PRETTY_PRINT+JSON_UNESCAPED_SLASHES);
{
	"token_type": "Bearer",
	"scope": "https://outlook.office.com/SMTP.Send",
	"ext_expires_in": 3600,
	"access_token": "EwBFB+l3BAK...",
	"refresh_token": "M.C732_B...",
	"expires": 1689702075
}
php > 

// Retrieve token from storage.
$token = [ ... ];

// Refresh token if it is expiring in say a minute.
$ttl = 60;
$oauth2 = new PL2010\OAuth2\OAuth2Provider(...);
$refreshed = $oauth2->refresh($token, $ttl);
if ($refreshed !== null) {
	// Save refreshed token to storage.
	...
	$token = $refreshed;
}

// Use $token ...

php > // Create manager.
php > $manager = new PL2010\OAuth2\OAuth2Manager;
php > // Configure 'google' provider for 'drive' and 'openid' purposes.
php > $manager->configure('google', [
	'provider' => [
		'client_id' => ...,
		'client_secret' => ...,
		'url_access_token' => 'https://oauth2.googleapis.com/token',
		'url_authorize' => 'https://accounts.google.com/o/oauth2/auth',
	],
	'usage' => [
		'drive' => [
			'scopes' => [
				'https://www.googleapis.com/auth/drive.file',
				'https://www.googleapis.com/auth/drive.resource',
				...
			],
		],
		'signin' => [
			'scopes' => [
				'openid',
				'email',
				...
			],
		],
	],
]);
php > // Configure 'microsoft' provider for 'smtp'.
php > $manager->configure('microsoft', [
	'provider' => [
		'client_id' => ...,
		'client_secret' => ...,
		'url_access_token' => 'https://login.microsoftonline.com/common/oauth2/v2.0/token',
		'url_authorize' => 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize',
	],
	'usage' => [
		'smtp' => [
			'scopes' => [
				'https://graph.microsoft.com/mail.send',
			],
		],
	]
]);

php > $oauth2 = $manager->get('microsoft', 'smtp');
php > // Like before ...
php > $scope = [ 'https://outlook.office.com/SMTP.Send', 'offline_access' ];
php > $url = $oauth2->authorize('code', $scope);
...


return [
	'google' => [
		'provider' => [
			'client_id' => ...,
			'client_secret' => ...,
			...
		],
		'usage' => [
			'drive' => [
				...
			],
			'signin' => [
				...
			],
		],
	],

	'microsoft' => [
		'provider' => [
			'client_id' => ...,
			'client_secret' => ...,
			...
		],
		'usage' => [
			'smtp' => [
				...
			],
		]
	],
];

use PL2010\OAuth2\Repositories\DirectoryTokenRepository;

app()->singleton('oauth2_tokens', function() {
	return new DirectoryTokenRepository(
		storage_path('app/oauth2_tokens'),
		app('oauth2')
	);
});

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Route;

// Presumably there would a button on some page to do make a POST request,
// but for simplicity we just use `GET` in our example.
Route::get('/oauth2/authorize/{provider}/{usage?}', function(
	Request $request,
	string $provider,
	?string $usage=null
) {
	/**
	 * @var \PL2010\OAuth2\OAuth2Manager $mgr
	 * @var \PL2010\OAuth2\OAuth2Provider $oauth2
	 */
	$mgr = app('oauth2');
	$oauth2 = $mgr->get($provider, $usage);
	$redirect = route('oauth2.callback', [
		'provider' => $provider,
		'usage' => $usage,
	]);
	$url = $oauth2->authorize('code', '', $redirect, function($state, $data) {
		// Preserve state data in cache for a short while.
		Cache::put("oauth2:flow:state:{$state}", $data, now()->addMinutes(15));
	});
	return redirect($url);
})->middleware([
	// There would be middlewares appropriate for the use case.
	'can:configureOAuth2',
])->name('oauth2.authorize');

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Route;

// Handle redirect from OAuth2 authorization provider.
Route::get('/oauth2/callback/{provider}/{usage?}', function(
	Request $request,
	string $provider,
	?string $usage=null
) {
	/**
	 * @var \PL2010\OAuth2\OAuth2Manager $mgr
	 * @var \PL2010\OAuth2\OAuth2Provider $oauth2
	 * @var \PL2010\OAuth2\Contracts\TokenRepository $tkrepo
	 */
	// Expect authorization state in the request.
	$state = $request->get('state');
	if (!is_string($state))
		return redirect('/')->with('error', 'Missing OAuth2 state');

	// Retrieve preserved state data.
	$data = Cache::get("oauth2:flow:state:{$state}");
	if (!$data)
		return redirect('/')->with('error', 'Invalid OAuth2 state');

	// Obtain access token.
	$mgr = app('oauth2');
	$oauth2 = $mgr->get($provider, $usage);
	$token = $oauth2->receive($request->fullUrl(), preserved:$data);

	// Save access token.
	$key = $provider.($usage != ''
		? ":{$usage}"
		: ''
	);
	$tkrepo = app('oauth2_tokens');
	$tkrepo->putOAuth2Token($key, $token);

	return redirect('/')->with('success', 'OAuth2 access token saved');
})->middleware([
	// There would be middlewares appropriate for the use case.
	'can:configureOAuth2',
])->name('oauth2.callback');
shell
$ composer 
shell
$ git clone https://github.com/plai2010/php-oauth2.git
$ cd php-oauth2
$ composer install
shell
$ php -a
Interactive shell

php >