How to Get Session Token in AWS?
Last Updated :
16 Sep, 2024
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:
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:
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.
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:
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.
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)
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.
Similar Reads
How To Get The API Token For Jenkins ?
Jenkins is an open-source automation tool that automates the build, test, and deployment stages of software. In this guide, I will first discuss what Jenkins is. Then I would discuss why to generate API tokens in Jenkins. After this, I will guide you through the different steps to generate an API to
4 min read
How to Install R on AWS EC2?
R is widely used as a different programming language. There are several programming languages are present for different purposes. The C programming language is used to get basic knowledge in the programming field. Java programming language is used to get some deep knowledge of programming & its
7 min read
How to create an IAM user in AWS
In this, the title IAM stands for Identity Access Management. When we working on cloud services in a company. Different employee has different categories of access. The employees in the company are restricted to particular resource utilization and Administration has the complete access to review all
5 min read
How to Use AWS Secrets Manager in Spring Boot?
AWS secret manager is most popular AWS service used for storing service secrets and other environment variables used for deploying applications. Spring applications use most of the variables defined in the application.properties file. In this article, we will see how to use AWS secret manager in Spr
4 min read
How to Install Python 2.8 on AWS EC2?
AWS or Amazon Web Services is one of the biggest cloud services providers with a variety of services such as on-demand computational services, databases, storage space, etc. EC2 or Elastic Compute Cloud is one of its services which acts as an on-demand computing service on the cloud platform. From a
4 min read
How to Get Object in AWS S3 Using UI & CLI ?
The Amazon Web Services (AWS) Simple Storage Service (S3) is a scalable object storage service that allows you to store and retrieve any amount of data at any time. The AWS SDK for JavaScript in Node.js provides the getObject method, which can be used to download objects from S3. This article will s
5 min read
How To Create An SSH key In Terraform ?
AWS SSH keys are private secret keys used for various access related things in AWS. These can be used for resources such as EC2 instances, IAM accounts. etc. Terraform can be used for easy and direct creation of SSH key in AWS. Let's see how we can create SSH Key using Terraform. Primary Components
4 min read
How to Create and View Access Tokens in NPM ?
Access tokens are important components in the npm ecosystem, used as authentication mechanisms for users to interact with npm registries securely. They grant permissions for actions such as publishing packages, accessing private packages, or managing user accounts. In this article, we will see how t
2 min read
How to get AWS Account Id in Lambda
AWS Lambda is a FaaS (Function as a Service) provided by Amazon Web Services. It is a compute service which can be used to run code in response to an event without provisioning or managing servers making it an optimal choice for creating event-driven serverless applications. AWS Lambda provides high
6 min read
How To Configure SAML In AWS
For enterprises configuring the SAML(Security Assertion Markup Language) is essential for providing an optimized and secured approach to user authentication and authorization. This article guides you in implementing the essential steps within the AWS ecosystem from making an understanding of SAML fu
9 min read