Simple PHP code for AWS Cognito OAuth2 authentication and extract client data from user pool
require '<your-path>/vendor/autoload.php';
use Aws\CognitoIdentityProvider\CognitoIdentityProviderClient;
use Aws\Exception\AwsException;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Uri;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
$clientId = '<YOUR-CLIENT-ID>';
$accessKey = '<YOUR-AWS-ACCESS-KEY>';
$clientSecret = '<YOUR-AWS-CLIENT-SECRET>';
$userPoolId = '<YOUR-AWS-USER-POOL-ID>';
$tokenUrl = 'https://<DOMAIN>.auth.<YOUR-REGION>.amazoncognito.com/oauth2/token';
$redirectUri = '<YOUR-REDIRECT-URL>';
$authorizationCode = $_GET['code'];
$credentials = new Credentials($this->accessKey, $this->clientSecret);
try{
$handlerStack = HandlerStack::create();
$handlerStack->push(Middleware::mapRequest(function ($request) {
return $request->withHeader('verify', false);
}));
// Create a client with the customized handler stack
$client = new Client([
'handler' => $handlerStack,
'verify' => false,
]);
$response = $client->post($this->tokenUrl, [
'form_params' => [
'Content-Type' =>'application/x-www-form-urlencoded\r\n',
'grant_type' => 'authorization_code',
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret,
'code' => $authorizationCode,
'redirect_uri' => $this->redirectUri,
'verify' => false,
],
]);
$responseBody = $response->getBody()->getContents();
$tokenData = json_decode($responseBody, true);
// Get the ID token and access token
$accessToken = $tokenData['access_token'];
$refresh_token = $tokenData['refresh_token'];
$idToken = $tokenData['id_token'];
error_log("getAccessCode3 idToken : $idToken");
// Decode the ID token to get user data
$decodedIdToken = json_decode(
base64_decode(
str_replace('_',
'/',
str_replace('-', '+', explode('.', $idToken)[1]))),
true);
// Print user data
error_log('getAccessCode3 User ID: ' . $decodedIdToken['sub'] );
error_log('getAccessCode3 Username: ' . $decodedIdToken['cognito:username'] );
error_log('getAccessCode3 Email: ' . $decodedIdToken['email'] );
}catch(AwsException $e){
error_log("getAccessCode3 AwsException : " . $e->getMessage());
}
Comments
Post a Comment