Skip to content

AssumeRole API - Authorization

0

We are using the assumeRole API with the required parameters but the API is expecting a AWS signature that is to be sent as the Auth Parameters. Could you help us in understanding how exactly we can generate a temporary token to be parsed as the Auth parametrs for the assume Role API.

Please find the Request parameters being sent and the response below:

  • Request: Request
  • Reponse : Response
4 Answers
0

You need to ensure you fill out the AWS required Parameters in the Authorization Tab which includes the IAM Access Key, Secret and Session Token

EXPERT

answered 2 years ago

  • Hi Gary,

    Thank you for the response

    As per my understanding of the API docs, the assumeRole API is used to generate a temporary credentials right, but then what we don't understand how exactly are we supposed to use the SDKs to generate the signature. we have been using node.js to execute a script but the script requires the accessID and the secretkey and we weren't sure on where to generate these details from.

    Could you guide us in case we are taking the wrong approach

    Thanks in advance Roshan Raj

  • Where are you running the node.js script from?

  • We have been executing the JavaScript code in the node.js command terminal and we have tried to execute a script on the prescript tab of the postman console as well.

0

Hi,

All requests that you make to AWS service API need to be signed with the SigV4 protocol: https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html

You follow the above to code your signature algorithm but it's quite some work.

My recommendation is to call AWS APIs using the SDK of your preferred language. AWS supports multiple languages: https://aws.amazon.com/developer/tools/

And if you don't want to use any AWS SDK, you can at least download its source code for your preferred language to see (and use... : it's OSS) its code to create your own signing code.

Best,

Didier

EXPERT

answered 2 years ago

EXPERT

reviewed 2 years ago

  • Hi Didier

    Thank you for the response

    We have been using AWS SDK's and node.js to execute a script that generates the signature required to be sent as the auth parameters for the assumeRole API but our question comes here where the script we have been using expects the accessKey, the secretKey to be sent as part of the script to create the said signature and we aren't sure where we are to generate these credentials from.

    Find the code snippet attached for reference - const accessKey = 'YOUR_ACCESS_KEY'; const secretKey = 'YOUR_SECRET_KEY'; const region = 'us-east-1'; const service = 'sts'; const method = 'POST'; const uri = '/'; const body = 'Action=AssumeRole&RoleArn=arn:aws:iam::123456789012:role/PegaSNSRole&RoleSessionName=MySession&Version=2011-06-15'; const headers = {};

    const { authorizationHeader, headers: signedHeaders } = signRequest(accessKey, secretKey, region, service, method, uri, body, headers);

    console.log('Authorization:', authorizationHeader); console.log('Signed Headers:', signedHeaders);

    Could you help guide us in achieving this please

    Thanks in Advance Roshan Raj

0

Does this work for you??

const AWS = require('aws-sdk');

// Your IAM access key and secret
const ACCESS_KEY = 'YOUR_ACCESS_KEY';
const SECRET_KEY = 'YOUR_SECRET_KEY';

// Configure AWS SDK
AWS.config.update({
  accessKeyId: ACCESS_KEY,
  secretAccessKey: SECRET_KEY,
  region: 'us-east-1', // Adjust to your desired region
});

const sts = new AWS.STS();

async function assumeRole() {
  const params = {
    RoleArn: 'arn:aws:iam::123456789012:role/YourRoleName', // Replace with the ARN of the role to assume
    RoleSessionName: 'YourSessionName', // A unique session name
  };

  try {
    const data = await sts.assumeRole(params).promise();
    console.log('Assumed Role Credentials:', data.Credentials);

    // Use the temporary credentials to make further AWS SDK calls
    const tempCredentials = {
      accessKeyId: data.Credentials.AccessKeyId,
      secretAccessKey: data.Credentials.SecretAccessKey,
      sessionToken: data.Credentials.SessionToken,
    };

    // Example: Use the assumed role credentials to list S3 buckets
    const s3 = new AWS.S3(tempCredentials);

    const s3Buckets = await s3.listBuckets().promise();
    console.log('S3 Buckets:', s3Buckets);
  } catch (error) {
    console.error('Error assuming role:', error);
  }
}

assumeRole();
EXPERT

answered 2 years ago

  • Hi Gary

    Thank you for the code snippet, but we are trying to generate the STS token by using an IAM Role rather than an IAM user as per enterprise policies, Also this service has to be consumed by an application that might not be hosted on AWS.

    Also, could you suggest if this could be a feasible alternative to achieve this requirement - Creating API Gateway to Forward Requests to SNS

0

Appoligies as you had IAM Keys in the original question i thought it was running as a user than a Role.. You need to extract the IAM keys and tokens when trying to assume the new role

How about

const AWS = require('aws-sdk');

exports.handler = async (event) => {
    // Configure STS
    const sts = new AWS.STS();

    try {
        // Assume the target role
        const assumeRoleResponse = await sts.assumeRole({
            RoleArn: 'arn:aws:iam::123456789012:role/TargetRoleName', // Replace with your target role ARN
            RoleSessionName: 'SessionName' // Unique identifier for the session
        }).promise();

        // Extract temporary credentials
        const { AccessKeyId, SecretAccessKey, SessionToken } = assumeRoleResponse.Credentials;

        // Use temporary credentials to configure a new AWS service client
        const s3 = new AWS.S3({
            accessKeyId: AccessKeyId,
            secretAccessKey: SecretAccessKey,
            sessionToken: SessionToken
        });

        // Example S3 call using temporary credentials
        const s3Response = await s3.listBuckets().promise();

        console.log('S3 Buckets:', s3Response.Buckets);

        return {
            statusCode: 200,
            body: JSON.stringify({ message: 'AssumeRole success', buckets: s3Response.Buckets })
        };
    } catch (error) {
        console.error('Error assuming role:', error);
        return {
            statusCode: 500,
            body: JSON.stringify({ message: 'Error assuming role', error: error.message })
        };
    }
};
EXPERT

answered 2 years ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.