Introduction#
- Login using cognito userpool
- Exchange for credentials
- credentials from cognito identity pool
Cognito Client#
Let create a cognito client
import { fromCognitoIdentityPool } from '@aws-sdk/credential-providers'import {CognitoIdentityProviderClient,InitiateAuthCommand,AdminSetUserPasswordCommand} from '@aws-sdk/client-cognito-identity-provider'import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3'// cognito clientconst cognitoClient = new CognitoIdentityProviderClient({region: 'ap-southeast-1'})const setpass = async () => {const response = await cognitoClient.send(new AdminSetUserPasswordCommand({Password: '',Username: '',UserPoolId: 'user_pool_id',Permanent: true}))console.log(response)}
Login UserPool#
const login = async (): Promise<any> => {const response = await cognitoClient.send(new InitiateAuthCommand({AuthFlow: 'USER_PASSWORD_AUTH',AuthParameters: {USERNAME: '',PASSWORD: ''},ClientId: ''}))// exchange login for credentialsif (response['AuthenticationResult']) {// console.log(response["AuthenticationResult"]);} else {}return response}
Get Credentials#
Let get credentials after logged in
const getCredentials = async () => {const response = await login()// console.log(response);const credential = fromCognitoIdentityPool({clientConfig: { region: 'ap-southeast-1' },identityPoolId: 'ap-southeast-1:653a7da6-1df6-41a6-b318-680e770968a0',logins: {['cognito-idp.ap-southeast-1.amazonaws.com/user_pool_id']:response['AuthenticationResult']!['IdToken']!}})const retrieves = await credential.call(this)console.log(retrieves)}
Cognito Identity Pool#
Let setup credentials from identity pool
const s3Client = new S3Client({region: 'us-east-1',credentials: fromCognitoIdentityPool({clientConfig: { region: 'ap-southeast-1' },identityPoolId: 'ap-southeast-1:653a7da6-1df6-41a6-b318-680e770968a0'// logins: {// ["cognito-idp.ap-southeast-1.amazonaws.com/user_pool_id"]:// response["AuthenticationResult"]!["IdToken"]!,// },})})const reponse = await s3Client.send(new PutObjectCommand({Bucket: 'cdk-entest-videos',Key: 'web-entest/hehe1.txt',Body: 'Hello'}))console.log(response)