Skip to content

Instantly share code, notes, and snippets.

@LuisCusihuaman
Last active May 4, 2024 21:03
Show Gist options
  • Save LuisCusihuaman/4a32294490ffb7e69ae1a881a9d6025f to your computer and use it in GitHub Desktop.
Save LuisCusihuaman/4a32294490ffb7e69ae1a881a9d6025f to your computer and use it in GitHub Desktop.
import { CognitoIdentityProviderClient, GetIdCommand, GetCredentialsForIdentityCommand } from '@aws-sdk/client-cognito-identity';
import { S3Client } from '@aws-sdk/client-s3';
// Configuration
const REGION = 'us-east-1';
const userPoolId = import.meta.env.VITE_USER_POOL_ID;
const identityPoolId = import.meta.env.VITE_IDENTITY_POOL_ID;
// Initialize S3Client without specific credentials
export const s3Client = new S3Client({ region: REGION });
// Function to update S3Client credentials
export async function updateS3ClientCredentials() {
const cognitoIdentityClient = new CognitoIdentityProviderClient({ region: REGION });
try {
const getIdParams = {
IdentityPoolId: identityPoolId,
Logins: {
[`cognito-idp.${REGION}.amazonaws.com/${userPoolId}`]: sessionStorage.getItem('access_token') // Using sessionStorage to get the access token
}
};
const idResponse = await cognitoIdentityClient.send(new GetIdCommand(getIdParams));
const getCredentialsParams = {
IdentityId: idResponse.IdentityId,
Logins: {
[`cognito-idp.${REGION}.amazonaws.com/${userPoolId}`]: sessionStorage.getItem('access_token')
}
};
const credentialsResponse = await cognitoIdentityClient.send(new GetCredentialsForIdentityCommand(getCredentialsParams));
const credentials = credentialsResponse.Credentials;
s3Client.config.credentials = {
accessKeyId: credentials.AccessKeyId,
secretAccessKey: credentials.SecretKey,
sessionToken: credentials.SessionToken
};
console.log('S3 Client credentials updated and ready to use.');
} catch (error) {
console.error('Failed to update S3 client credentials:', error);
}
}
// This function should be called after user login and the access token is stored in sessionStorage.
updateS3ClientCredentials();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment