PHP code example of tj09 / dragon-cave-oauth

1. Go to this page and download the library: Download tj09/dragon-cave-oauth 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/ */

    

tj09 / dragon-cave-oauth example snippets




ider = \DragonCave\API\OAuth\DragonCaveOAuthProvider([
	'clientId' => 'my.client.id',
	'clientSecret' => 'secret',
	'redirectUri' => 'http://localhost',
	'pkceCode' => $_SESSION['oauth_pkce'] ?? null,
]);

if (!isset($_GET['code'])) {
	$url = $oauth->getAuthorizationUrl([
		'scope' => ['identify', 'dragons'],
	]);

	// TODO: Actually managing session state is left as an exercise to the reader.
	$_SESSION['oauth_state'] = $oauth->getState();
	$_SESSION['oauth_pkce'] = $oauth->getPkceCode();

	header('Location: '.$url);
	die();
}

if (!isset($_SESSION['oauth_state']) || !isset($_SESSION['oauth_pkce']) || $request->getString('state') !== $_SESSION['oauth_state']) {
	unset($_SESSION['oauth_state']);
	unset($_SESSION['oauth_pkce']);

	// TODO: This is not a helpful error message for people using your application.
	echo 'Invalid state';
	die();
}

unset($_SESSION['oauth_state']);
unset($_SESSION['oauth_pkce']);

try {
	$token = $oauth->getAccessToken('authorization_code', [
		'code' => $_GET['code'],
	]);
} catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
	// TODO: Consider logging the exception.
	echo 'Failed to verify your login with Dragon Cave.';
	die();
}

$oauth_user = $oauth->getResourceOwner($token);

$_SESSION['dcAccessToken'] = $token->getToken();

// TODO: store some information about $oauth_user.
echo "Welcome, {$oauth_user->getUsername()}!";