Continuing from my last blog, I started accessing the S3 bucket as an Amazon Cognito user using PowerShell. After all, the idea was to create a script to access S3 resources using access/refresh tokens.
First, I thought it is going to be trivial. Like many other APIs AWS PowerShell module implementations will have one-to-one commandlets to pretty much convert the CLI script to PowerShell – well, I was wrong.
To start with, commands are spread across various modules; each has very similar sounding API commands that does different things. Then, it was challenging to find out where to send the REST request – still, if you search the web, it is apparent that there is confusion on should it be sent to the common amazon gateway or your Coginto endpoint. It was the former - I had to ran a good old network trace to find out where the CLI command sends the request
Another challenge was figuring out how to send data. I hadn’t used AWS gateway with HTTP posts before, so it took a while to figure out the exact methods. Parameters are spread across the header and post body.
After that it is reasonably straightforward. Once you get an id_token for the Cognito user,
Use API
com.amazonaws.cognito.identity.model.AWSCognitoIdentityService.GetId
to get the id pool identity. This is not strictly necessary as it is shown under identity browser in the identity pool, but this call makes it more generalized.
Then use the following API to get the credentials.
com.amazonaws.cognito.identity.model.AWSCognitoIdentityService.GetCredentialsForIdentity
https://cognito-identity.<region>
Finally, this was the script.
$id_tkn = "<id_token>" $identityPoolId = "<region>:<GUID>" $id_provider = "cognito-idp.<region>.amazonaws.com/<userpool_id>" $idbody = @" { "IdentityPoolId": "$identityPoolId", "Logins": { "$id_provider":"$id_tkn" } } "@ $idheaders=@{'X-AMZ-TARGET'='com.amazonaws.cognito.identity.model. AWSCognitoIdentityService.GetId'; 'CONTENT-TYPE' = 'application/x-amz-json-1.1' } $credheaders=@{'X-AMZ-TARGET'='com.amazonaws.cognito.identity.model. AWSCognitoIdentityService.GetCredentialsForIdentity'; 'CONTENT-TYPE' = 'application/x-amz-json-1.1'} $id = Invoke-RestMethod -uri https://cognito-identity.<region>.amazonaws.com -Method Post -Body $idbody -Headers $idheaders $IdentityId = $id.IdentityId $credBody= @" { "IdentityId": "$IdentityId", "Logins": { "$id_provider":"$id_tkn" } } "@ $cred = Invoke-RestMethod -uri https://cognito-identity.<region>.amazonaws.com -Method Post -Body $credbody -Headers $credheaders $accKey = $cred.Credentials.AccessKeyId $secretKey = $cred.Credentials.SecretKey $sessionTkn = $cred.Credentials.SessionToken read-s3object -bucketname <bucket or accesspoint name> -key <item_key> -File <local file name to store> -AccessKey $accKey -SecretKey $secretKey -SessionToken $sessionTkn