Skip to content

Instantly share code, notes, and snippets.

@saiumesh535
Last active June 20, 2023 11:30
Show Gist options
  • Save saiumesh535/146479fa79e869eabf154a3dca41e6c7 to your computer and use it in GitHub Desktop.
Save saiumesh535/146479fa79e869eabf154a3dca41e6c7 to your computer and use it in GitHub Desktop.
configure AWS temp credentials
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
import AWS, { Route53, S3 } from 'aws-sdk';
import { createHmac } from 'crypto';
type ObjectLike = Record<string, unknown> | string | Error | unknown;
export type CognitoAuthToken = {
AuthenticationResult: {
IdToken: string;
};
};
export const COGNITO_AUTH_URL = 'https://cognito-idp.us-east-1.amazonaws.com';
export const COGNITO_USER_PASSWORD_AUTH = 'USER_PASSWORD_AUTH';
export const getCognitoLoginKey = (
region: string,
userPoolId: string
): string => {
return `cognito-idp.${region}.amazonaws.com/${userPoolId}`;
};
export const COGNITO_AUTH_HEADERS = {
'X-Amz-Target': 'AWSCognitoIdentityProviderService.InitiateAuth',
'Content-Type': 'application/x-amz-json-1.1',
}
export type CognitoAuthInput = {
secret: string;
clientId: string;
username: string;
password: string;
userPoolId: string;
identityPoolId: string;
region: string;
};
;
export const postAPI = async <T = ObjectLike, R = unknown>(
url: string,
body?: T,
config?: AxiosRequestConfig
): Promise<AxiosResponse<R>> => {
return axios.post(url, body, config);
};
export const getCognitoHash = (input: CognitoAuthInput): string => {
return createHmac('SHA256', input.secret)
.update(`${input.username}${input.clientId}`)
.digest('base64');
};
const getAuthCode = async (input: CognitoAuthInput): Promise<string> => {
const secretHash = getCognitoHash(input);
const response = await postAPI<ObjectLike, CognitoAuthToken>(
COGNITO_AUTH_URL,
{
AuthParameters: {
USERNAME: input.username,
PASSWORD: input.password,
SECRET_HASH: secretHash,
},
AuthFlow: COGNITO_USER_PASSWORD_AUTH,
ClientId: input.clientId,
},
{
headers: COGNITO_AUTH_HEADERS,
}
);
return response.data?.AuthenticationResult?.IdToken;
};
export const configureCredentials = async (
input: CognitoAuthInput
): Promise<void> => {
const authCode = await getAuthCode(input);
AWS.config.region = input.region;
const key = getCognitoLoginKey(input.region, input.userPoolId);
const credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: `${input.region}:${input.identityPoolId}`,
Logins: {
[key]: authCode,
},
});
await credentials.getPromise();
AWS.config.credentials = credentials;
const s3 = new S3();
console.log(
`There are ${
(await s3.listBuckets().promise()).Buckets?.length || 0
} buckets`
);
};
await configureCredentials({
clientId: 'XXXXXXXXXX',
identityPoolId: 'XXXXXXX',
password: 'XXXXX',
region: 'us-east-1',
secret: 'XXXXXX',
username: 'XXXXXX',
userPoolId: 'XXXXXXX',
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment