Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bastman/7784ffc371eac40d12e8f72a9088bcca to your computer and use it in GitHub Desktop.
Save bastman/7784ffc371eac40d12e8f72a9088bcca to your computer and use it in GitHub Desktop.
aws cognito examples (bash / php): custom auth provider

Aws Cognito: Custom Auth (Developer Authenticated Identities)

How to get OpenID Token & IdentityId from AWS Cognito?

  • example: using bash (aws cli sdk)
  • example: using php (aws php sdk v3.*)

note

  • you need to add example.com as custom auth provider in aws console (cognito/federated)
  • you need to add IAM policies ("cognito") to your aws access key/secret

verify tokens

AWS User Pool: Example

OpenId (custom auth): Example

contains link to ...

#!/usr/bin/env bash
export AWS_ACCESS_KEY_ID=<KEY_ID>
export AWS_SECRET_ACCESS_KEY=<SECRET>
aws cognito-identity get-open-id-token-for-developer-identity --cli-input-json file://./get-open-id-token-for-developer-identity.json --region "us-east-1"
{
"IdentityPoolId": "us-east-1:XXXXX",
"Logins": {
"example.com": "mycustom-user-id"
},
"TokenDuration": 360
}
// php example (quick n dirty)
// ===========================
use Aws\CognitoIdentity\CognitoIdentityClient;
use Aws\Credentials\Credentials;
class GetOpenIdTokenForDeveloperIdentityCommand
{
// requires aws sdk 3.18.*
// $ composer require "aws/aws-sdk-php:^3.18"
/**
* @return array
*/
public static function createClientConfigFromCredentials($awsRegion, $awsKeyId, $awsSecretKey) {
$awsCredentials = new Credentials($awsKeyId, $awsSecretKey); // don't do that in production!
return [
'version' => 'latest',
'region' => $awsRegion,
'credentials'=>$awsCredentials,
];
}
/**
* @return array
*/
public static function createRequestParamsExample() {
return [
'IdentityPoolId'=>'<AWS_POOL_REGION>:<AWS_POOL_UID>',
'Logins'=>[
'example.com'=> '<YOUR_CUSTOM_AUTH_USER_ID>'
],
'TokenDuration'=>60*60,
];
}
/**
* @param array $clientConfig
* @return array
*/
public function run(array $clientConfig, array $requestParams) {
$client= new CognitoIdentityClient($clientConfig);
return $client->getOpenIdTokenForDeveloperIdentity($requestParams)
->toArray();
}
}
// main
$clientConfig=GetOpenIdTokenForDeveloperIdentityCommand::createClientConfigFromCredentials('us-east-1','<AWS_KEY_ID>,'<AWS_SCRET_ID>');
$requestParams=[
'IdentityPoolId'=>'us-east-1:<AWS_POOL_UID>',
'Logins'=>[
'example.com'=> 'my-custom-user-id-12345'
],
'TokenDuration'=>60*60,
];
$command=new GetOpenIdTokenForDeveloperIdentityCommand();
$result=$command->run($clientConfig, $requestParams);
echo json_encode($result);
@john-harbison
Copy link

Thanks so much for this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment