Tim
Tim

Reputation: 966

AWS Cognito user pool OAuth REST API call examples exist?

It feels like amazon are encouraging people to just use their client SDK, but it would be nice to see what a sequence of valid REST calls looks like for the authorization and implicit grant flows.

The AWS documentation for the authorization and token endpoints is a nice start: http://docs.aws.amazon.com/cognito/latest/developerguide/cognito-userpools-server-contract-reference.html

Does anybody know if some examples exist showing the sequence of REST calls for the Implicit and Authorization flows (against Cognito)?

Upvotes: 1

Views: 3650

Answers (2)

Joe Pietroni
Joe Pietroni

Reputation: 826

The documentation is a bit shoddy, but here's an example PHP cURL call to get the ID/Access Tokens using your authorization code for the Authorization flow:-

$url = 'https://<YOURDOMAIN>.auth.us-east-1.amazoncognito.com/oauth2/token';
$client_key = '<YOUR_CLIENT_ID>';
$client_secret = '<YOUR_CLIENT_SECRET>';

$data = [       'grant_type' => 'authorization_code',
                'client_id'=>$client_key, 'code'=>$_GET["code"],
                'redirect_uri'=>'<YOUR_REDIRECT_URI>'];

$handle = curl_init($url);
curl_setopt($handle, CURLOPT_VERBOSE, true);
curl_setopt($handle, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($handle, CURLOPT_USERPWD, $client_key . ":" . $client_secret);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
$field_string = http_build_query($data);
curl_setopt($handle, CURLOPT_POSTFIELDS, $field_string);
$resp = json_decode(curl_exec($handle),true);

Once you've got the ID token you need to parse the JWK JSON file from

https://cognito-idp.us-east-1.amazonaws.com/<USER_POOL_ID/.well-known/jwks.json

and then lookup the kid field in the token header, and use that as the secret to decode the token. I used this library:- https://github.com/firebase/php-jwt

So the token validation code looks something like:-

$jwks_json = file_get_contents("https://cognito-idp.us-east-1.amazonaws.com/<USER_POOL_ID>/.well-known/jwks.json");
$jwk = JWK::parseKeySet($jwks_json);

$tks = explode('.', <YOUR_TOKEN>);
list($headb64, $bodyb64, $cryptob64) = $tks;
$jwt_header = json_decode(base64_decode($headb64),true);
$jwt_body = json_decode(base64_decode($bodyb64),true);
$key=$jwk[$jwt_header["kid"]];

try
{
    $decoded = JWT::decode(<YOUR_TOKEN>, $key, array($jwt_header["alg"]));
    $decoded_array = (array) $decoded;
    // GREAT SUCCESS!
}
catch (\Exception $e)
{
    // TOKEN COULDN'T BE VALIDATED
}

Upvotes: 4

BryceH
BryceH

Reputation: 2798

I am not aware of anything with it nicely documented. I think your best option would be to spin up a test app using one of the SDKs and monitor the network traffic. It seems the API is not well documented.

Upvotes: 0

Related Questions