I' using Cognito user pool for securing my API gateway . Now I would like to make requests to my API using postman but I need to pass in Authorization token as the API is secured. Is there any AWS CLI command or REST API to generate auth tokens(by passing username/password)? I have searched documentation but couldn't find any examples. Thanks for your help.
You can do this using the following CLI commands:
Register a user
aws cognito-idp sign-up --region {your-aws-region} --client-id {your-client-id} --username admin#example.com --password password123
Confirm user registration
aws cognito-idp admin-confirm-sign-up --region {your-aws-region} --user-pool-id {your-user-pool-id} --username admin#example.com
Authenticate (get tokens)
aws cognito-idp admin-initiate-auth --region {your-aws-region} --cli-input-json file://auth.json
Where auth.json is:
{
"UserPoolId": "{your-user-pool-id}",
"ClientId": "{your-client-id}",
"AuthFlow": "ADMIN_NO_SRP_AUTH",
"AuthParameters": {
"USERNAME": "admin#example.com",
"PASSWORD": "password123"
}
}
You should get a response like this if everything is set up correctly:
{
"AuthenticationResult": {
"ExpiresIn": 3600,
"IdToken": "{your-idtoken}",
"RefreshToken": "{your-refresh-token}",
"TokenType": "Bearer",
"AccessToken": "{your-access-token}"
},
"ChallengeParameters": {}
}
Use the following command to generate the auth tokens, fill in the xxxx appropriately based on your cognito configuration,
aws cognito-idp initiate-auth --auth-flow USER_PASSWORD_AUTH --client-id xxxx --auth-parameters USERNAME=xx#xx.com,PASSWORD=xxxx
Note: You can use any one username or password under applicable cognito user pool.
The client can be found under general settings--> app client
The AccessKeyId and SecretAccessKey is not required as it already defined while setting up the aws cli. If not done use the following link to set that up first
https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html
There is an AWS CLI command to generate Auth Tokens. You can use InitiateAuth CLI Command for this.
Note: Make sure you have done the UserPool configuration matching the expected tokens.
Related
I am trying to understand the authentication flow for aws cognito-userpools and cognito-identitypools. I am hitting an error when trying to invoke aws cognito-identity get-id command as below:
I was able to successfully authenticate with the cognito-idp
> aws cognito-idp initiate-auth --client-id 8ik2s2uk8d9ekh7k3s1hstlgt --auth-flow USER_PASSWORD_AUTH --auth-parameters USERNAME=testuser#xxx.com,PASSWORD=Pxxx1 --profile dev1
{
"ChallengeParameters": {},
"AuthenticationResult": {
"AccessToken": "eyJraWQi..OiJSUzI1NiJ9.eyJvcmln...MOssACEgAsP-..A",
"ExpiresIn": 3600,
"TokenType": "Bearer",
"RefreshToken": "eyJj...IuxVj4Vv3EykM1ItEZkpSA",
"IdToken": "e..QCw"
}
}
After that trying to generate a Cognito ID, see an error.
aws cognito-identity get-id --identity-pool-id us-west-2:7exxx27-fxx4-4xxb-bc7c-1107c054e6de --login IdToken=eyJ.....Q3g4TDQ9IiwiYWxnIjoiUlMy
An error occurred (NotAuthorizedException) when calling the GetId operation: Invalid login token. Issuer doesn't match providerName
My end goal is to get the temporary credentials invoking the aws cognito-identity get-credentials-for-identity. However hitting another error with that.
> aws cognito-identity get-credentials-for-identity --identity-id "us-west-2:7ee6b627-f894-4b3b-bc7c-1107c054e6de" --profile dev1 --region us-west-2.
An error occurred (ResourceNotFoundException) when calling the GetCredentialsForIdentity operation: Identity 'us-west-2:7ee6b627-f894-4b3b-bc7c-1107c054e6de' not found.
Not sure how to progress here, any help would be appreciated.
Ok, I realized what I was doing wrong. Am able to get the complete auth flow working.
Initiate Authentication (cognito-idp)
~> aws cognito-idp initiate-auth \
--client-id 8ik2sxxxxh7k3s1hstlgt \
--auth-flow USER_PASSWORD_AUTH \
--auth-parameters USERNAME=bxxxur#wxxxxxx.com,PASSWORD=Pxxx1 --profile dev1
{
"ChallengeParameters": {},
"AuthenticationResult": {
"AccessToken": "whYhsUITzQQ3eBXAwI6VX7Gi7Dmv2eP3T1w",
"ExpiresIn": 3600,
"TokenType": "Bearer",
"RefreshToken": "RwrB-FIu6ZaQkv3AP_htR9QhD.hHZoXervix8HcvMnyi8oVw",
"IdToken": "Ngf2ZbCZZ-FJwY-7ptPGpKMdA7NjjYVX8hM7DA"
}
}
Get cognito pool ID
%~> aws cognito-identity get-id \
--identity-pool-id us-west-2:7ee6b627-f894-4b3b-bc7c-1107c054e6de \
--login cognito-idp.us-west-2.amazonaws.com/us-west-
2_BLcbQ9DHK=eyJraWQiOiJlMF.....Z20mCsfhv4RHy0GSdJxLvZkZ-
w10Gloz8cApb71QrvxY2vPvqq0klDvWzeA
{
"IdentityId": "us-west-2:bbc7f768-1a17-4c02-8f48-56d2e84c3947"
}
Get credentials for identity
~> aws cognito-identity get-credentials-for-identity \
--identity-id us-west-2:bbc7f768-1a17-4c02-8f48-56d2e84c3947 \
--login cognito-idp.us-west-2.amazonaws.com/us-west-
2_BLcbQ9DHK=eyJraWQ......sj5bOd3hu824g --profile dev1
{
"IdentityId": "us-west-2:bbc7f768-1a17-4c02-8f48-56d2e84c3947",
"Credentials": {
"AccessKeyId": "AS....O57QPE",
"SecretKey": "f....CJsfDV5Y2jW",
"SessionToken":"IQWvwc.......BDXm+5khWB5m/NWYUbf7leZ/Sk2f2y4Le",
"Expiration": 1641857034.0
}
}
thanks for greate packages!
I have problem when i create development with localstack using S3 service to create presignedurl post.
I have run localstack with SERVICES=s3 DEBUG=1 S3_SKIP_SIGNATURE_VALIDATION=1 localstack start
I have settings AWS_ACCESS_KEY_ID=test AWS_SECRET_ACCESS_KEY=test AWS_DEFAULT_REGION=us-east-1 AWS_ENDPOINT_URL=http://localhost:4566 S3_Bucket=my-bucket
I make sure have the bucket
> awslocal s3api list-buckets
{
"Buckets": [
{
"Name": "my-bucket",
"CreationDate": "2021-11-16T08:43:23+00:00"
}
],
"Owner": {
"DisplayName": "webfile",
"ID": "bcaf1ffd86f41161ca5fb16fd081034f"
}
}
I try create presigned url, and running in console with this
s3_client_sync.create_presigned_post(bucket_name=settings.S3_Bucket, object_name="application/test.png", fields={"Content-Type": "image/png"}, conditions=[["Expires", 3600]])
and have return like this
{'url': 'http://localhost:4566/kredivo-thailand',
'fields': {'Content-Type': 'image/png',
'key': 'application/test.png',
'AWSAccessKeyId': 'test',
'policy': 'eyJleHBpcmF0aW9uIjogIjIwMjEtMTEtMTZUMTE6Mzk6MjNaIiwgImNvbmRpdGlvbnMiOiBbWyJFeHBpcmVzIiwgMzYwMF0sIHsiYnVja2V0IjogImtyZWRpdm8tdGhhaWxhbmQifSwgeyJrZXkiOiAiYXBwbGljYXRpb24vdGVzdC5wbmcifV19',
'signature': 'LfFelidjG+aaTOMxHL3fRPCw/xM='}}
And i test using insomnia
and i have read log in localstack
2021-11-16T10:54:04:DEBUG:localstack.services.s3.s3_utils: Received presign S3 URL: http://localhost:4566/my-bucket/application/test.png?AWSAccessKeyId=test&Policy=eyJleHBpcmF0aW9uIjogIjIwMjEtMTEtMTZUMTE6Mzk6MjNaIiwgImNvbmRpdGlvbnMiOiBbWyJFeHBpcmVzIiwgMzYwMF0sIHsiYnVja2V0IjogImtyZWRpdm8tdGhhaWxhbmQifSwgeyJrZXkiOiAiYXBwbGljYXRpb24vdGVzdC5wbmcifV19&Signature=LfFelidjG%2BaaTOMxHL3fRPCw%2FxM%3D&Expires=3600
2021-11-16T10:54:04:WARNING:localstack.services.s3.s3_utils: Signatures do not match, but not raising an error, as S3_SKIP_SIGNATURE_VALIDATION=1
2021-11-16T10:54:04:INFO:localstack.services.s3.s3_utils: Presign signature calculation failed: <Response [403]>
what i missing, so i cannot create the presignedurl post ?
The problem is with your AWS configuration -
AWS_ACCESS_KEY_ID=test // Should be an Actual access Key for the IAM user
AWS_SECRET_ACCESS_KEY=test // Should be an Actual Secret Key for the IAM user
AWS_DEFAULT_REGION=us-east-1
AWS_ENDPOINT_URL=http://localhost:4566 // Endpoint seems wrong
S3_Bucket=my-bucket // Actual Bucket Name in AWS S3 console
For more information, try to read here and setup your environment with correct AWS credentials - Setup AWS Credentials
I am new to AWS Cognito. I have created a user in the user pool using aws cli by using the admin create user command. Then I am trying to log in using SSO, but it gives a
user doesn't exist
message.
Command to create user:
aws cognito-idp admin-create-user \
--user-pool-id POOLID \
--username USERNAME \
--temporary-password PASSWORD \
--user-attributes Name=email,Value=XXX Name=phone_number,Value=XXX\
--message-action SUPPRESS
URL to access cognito:
https://<domain_name>.us-east-1.amazoncognito.com/login?client_id=<clientId>&response_type=code&scope=email+openid&redirect_uri=<redirect-uri>
I have created a API Gateway and I have applied Cognito Authentication there. Here to have the API Call work I am using AWS CLI to get Token , Here is my CLI Code
aws cognito-idp admin-initiate-auth --user-pool-id us-west-2_leb660O8L --client-id 1uk3tddpmp6olkpgo32q5sd665 --auth-flow ADMIN_NO_SRP_AUTH --auth-parameters USERNAME=myusername,PASSWORD=mypassword
Now I want to use CURL Call instead of this CLI Call. I have found the code but all needs client secret here. I do not have client secret as my user pool is of Enable Signin for server-based authentication.
Please guide me how I can use that.
I have gone through
https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html
[What will be the EndPoint for Calling IntiateAuth Or AdminIntiateAuth]
&
https://docs.aws.amazon.com/cognito/latest/developerguide/token-endpoint.html
To Summarise this :
I want to get Id_Token Using Curl or Postman without Client Secret.
Thanks in advance
You can authenticate a user with the following request.
This is the endpoint of the InitiateAuth request.
Hope that this is useful for you
Method: POST
Endpoint: https://cognito-idp.{REGION}.amazonaws.com/
Content-Type: application/x-amz-json-1.1
X-Amz-Target: AWSCognitoIdentityProviderService.InitiateAuth
Body:
{
"AuthParameters" : {
"USERNAME" : "YOUR_USERNAME",
"PASSWORD" : "YOUR_PASSWORD"
},
"AuthFlow" : "USER_PASSWORD_AUTH", // Don't have to change this if you are using password auth
"ClientId" : "APP_CLIENT_ID"
}
And the response as the following
{
"AuthenticationResult": {
"AccessToken": "YOUR_ACCESS_TOKEN",
"ExpiresIn": 3600,
"IdToken": "YOUR_ID_TOKEN",
"RefreshToken": "YOUR_REFRESH_TOKEN",
"TokenType": "Bearer"
},
"ChallengeParameters": {}
}
Just sharing direct curl here may helpful to anyone
curl -X POST --data #user-data.json \
-H 'X-Amz-Target: AWSCognitoIdentityProviderService.InitiateAuth' \
-H 'Content-Type: application/x-amz-json-1.1' \
https://cognito-idp.<just-replace-region>.amazonaws.com/
file json user-data.json
{"AuthParameters" : {"USERNAME" : "sadfsf", "PASSWORD" : "password"}, "AuthFlow" : "USER_PASSWORD_AUTH", "ClientId" : "csdfhripnv7sq027kktf75"}
make sure your app client does not contain app-secret or create new app without secret. also inside app enable USER_PASSWORD_AUTH
I was looking through aws docs at https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html as I needed to update the address for a user. According to the docs it says it follows the openID spec which for an address is a json object. However it errors on anything that is not a string.
I'm using the aws cli and calling it like so:
aws cognito-idp admin-update-user-attributes --user-pool-id my_user_pool --username a#b.com --user-attributes Name=address,Value={"street_address": "123 Fake Street","locality": "Somewhere","postal_code":"AA1 1AA"}
the following also doesn't work:
aws cognito-idp admin-update-user-attributes --user-pool-id my_user_pool --username a#b.com --user-attributes Name=address,Value="123 Fake Street, Somewhere"
Parameter validation failed:
Invalid type for parameter UserAttributes[0].Value, value: ['123 Fake
Street', 'Somewhere'], type: <class 'list'>, valid types: <class 'str'>
Am I inputting something wrong or is aws docs incorrect and only allowing strings through
I just ran into this issue as well, I couldn't find a solve in any of the AWS documentation but if you escape the comma it works.
aws cognito-idp admin-update-user-attributes --user-pool-id my_user_pool --username a#b.com --user-attributes Name=address,Value="123 Fake Street\, Somewhere"