Open In App

How to Get Session Token in AWS?

Last Updated : 16 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

A session token is a popular concept that is used in AWS for giving access to some user or person for a limited amount of time, in this the user gets to access the AWS resources but only for a limited amount of time only.

The purpose of the session token is to have more security in the AWS system so that only the authorized party can access the resources, which is why it is important to know how to get the AWS session token.

Session tokens are important whenever we are working with multiple people who need to access our resources which are stored in the AWS platform, but when we need to provide them access for only a limited amount of time then using the concept of session token is very helpful because it can help us to give them the access and after the time frame the session will expire automatically.

Step-by-Step Process to Get Session Token

Step 1: Create an AWS Bucket

The first step is to create the AWS bucket, you can also choose the bucket that you have already created to get the session token for it as well, for this simply login to the AWS and click on the create bucket option:

Create AWS Bucket.

Step 2: Create Role for the Bucket

The next step is to create a role for the bucket so that we can attach a policy, a role is used to give access to the resources from one account to another. For this simply go to roles > create role. After this open the role:

Create Role for the Bucket.

Step 3: Add Policy to Resource

The next step is to add the policy into the bucket, for this scroll down in the role and you will see the option “Attach Policy” it is required to add any one of the policy in the AWS in order to generate the session token, here we are going to select the AmazonS3FullAccess policy but for your requirements select the appropriate policy.

Add Policy to Resource.

Step 4: Create Code Files

The next step is to add following code which are required for getting the AWS session token and testing if it connects to the server correctly or not.

Following is the file structure for the code:

Create Code Files.

Here we are using two code files one is sessionToken.js and another one is the clientToken.js, lets add the necessary code in each of them for getting the session token.

Step 5: sessionToken.js File

Following is the code required in the sessionToken.js file, here we have first defined a user with userID and then use the resource parameter to list the required buckets for which we need to generate the session token.

// sessionToken.js

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

const sts = new AWS.STS({apiVersion: '2011-06-15'});

const userId = 123;

const YOURBucketPolicy =
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualStudioCode",
"Effect": "Allow",
"Action": [
"s3:PutObject",
"s3:GetObject"
],
"Resource": [
"arn:aws:s3:::YOUR-bucket-1/${userId}/*",
"arn:aws:s3:::YOUR-bucket-2/${userId}/*"
]
}
]
};

const role = {
RoleArn: 'arn:aws:iam::YOUR-ROLE-ID:role/webClientRole',
Policy: YOURBucketPolicy,
RoleSessionName: 'webClientRole',
DurationSeconds: 3600 // 3600 = 1 hour.
};

sts.assumeRole(role, (err, data) => {
console.log({
accessKeyId: data.Credentials.AccessKeyId,
secretAccessKey: data.Credentials.SecretAccessKey,
sessionToken: data.Credentials.SessionToken
});
});

In the end, we have defined the role we have given and also defined the required duration until the session token can last before they expire, once we execute this code in the terminal we will get the session token.

Session Token Generated.

Step 6: clientToken.js File

After the session token is generated successfully, we wil have to pass it to the clientToken.js file so that the client or end user can successfully check wether it is being connected to the AWS via the session token or not.

After obtaining the required parameters from the sessionToken.js file, now we will paste it into the clientToken.js file.

// clientSession.java

const fs = require('fs');
const AWS = require('aws-sdk');
const body = fs.createReadStream('./helloworld.txt');

AWS.config.update({
region: 'us-east-1', // add YOUR bucket region here.
accessKeyId: 'YOUR-ACCESS-KEY-ID',
secretAccessKey: 'YOUR-secretAccessKey',
sessionToken: 'YOUR-sessionToken'});

const s3 = new AWS.S3();

const params = {
Body: body,
Bucket: 'YOUR-bucket-1',
Key: '123/helloworld.txt'
};

s3.putObject(params, (err, data) => {
if (err) {
console.log(err.message);
} else {
console.log(data);
}
});

In this code file we are simply defining the required parameters for connecting using the session token, if it is connected successfully then it will write the Etag which is an entity tag of the object, it represents the hash of the object as entity, so that we know for sure that the session token is working.

Step 7: Running Script in Terminal

Last step is to run the clientToken.js js in the terminal to check whether it is giving the etag or not, for this we will run the terminal (you can use keyboard shortcut CTRL+Alt+N for running the script in visual studio code)

Running Script in Terminal.

As we can see in the terminal window, the output is showing the Etag as well, which means that the session token is generated and working correctly as well.

Conclusion

Generating and handling the session token is an important process in making sure that the access is being provided to the right user, it also maintains a time limit set by the administrator at the time of creating the session token so that the end user can not misuse it. Following the steps mentioned above can help in managing and creating the session token in AWS.


Next Article
Article Tags :

Similar Reads