Skip to content

Instantly share code, notes, and snippets.

@krnbr
Last active December 5, 2022 00:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krnbr/670ae3bd5b3fe8ef8593067c762f34ed to your computer and use it in GitHub Desktop.
Save krnbr/670ae3bd5b3fe8ef8593067c762f34ed to your computer and use it in GitHub Desktop.
STS goto console - programmatically
import {STSClient, AssumeRoleCommand, AssumeRoleCommandOutput} from "@aws-sdk/client-sts";
import axios from "axios";
// Set the AWS Region.
const REGION = "ap-south-1"; // otherwise copy your region from here - https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html#concepts-available-regions
const stsClient = new STSClient({ region: REGION, credentials: {
accessKeyId: '<replace with aws access key id>',
secretAccessKey: '<replace with aws secret access key>'
}});
export { stsClient };
export class AWSStsAssumeRole {
static async callAWSForSTSAssumeRole (): Promise<string> {
let cmd = new AssumeRoleCommand({
RoleArn: '<role arn that you want to assume using below code>',
RoleSessionName: '<just an identifier>',
DurationSeconds: 43200
});
let output: AssumeRoleCommandOutput = await stsClient.send(cmd);
// uncomment to explore this
// console.log(output.Credentials.SessionToken);
// console.log(output.Credentials);
let sessionBody = `{"sessionId":"${output.Credentials.AccessKeyId}","sessionKey":"${output.Credentials.SecretAccessKey}","sessionToken":"${output.Credentials.SessionToken}"}`;
let sessionBodyEncoded = encodeURIComponent(sessionBody);
let getSignInTokenUrl: string = "https://signin.aws.amazon.com/federation?Action=getSigninToken&DurationSeconds=43200&SessionType=json&Session="+sessionBodyEncoded
let signInTokenUrlResponse = await axios.get(getSignInTokenUrl);
let signInToken = signInTokenUrlResponse.data.SigninToken;
let consoleLoginUrl = `https://signin.aws.amazon.com/federation?Action=login&DurationSeconds=43200&SigninToken=${encodeURIComponent(signInToken)}&Destination=${encodeURIComponent(`https://${REGION}.console.aws.amazon.com/console`)}`
// console.log(getSignInTokenUrl);
// console.log(consoleLoginUrl);
return consoleLoginUrl;
}
}
AWSStsAssumeRole.callAWSForSTSAssumeRole().then((consoleLoginUrl) => console.log("click(or copy) this -> ", consoleLoginUrl));
{
"name": "aws-sts-explore",
"dependencies": {
"@aws-sdk/client-sts": "^3.201.0",
"aws-sdk": "^2.1245.0",
"axios": "1.1.0"
},
"devDependencies": {
"@types/node": "^14",
"ts-node": "^10.9.1",
"typescript": "^4.8.4"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment