Using AWS SDK2 to Authenticate and Get a Session Token

Using AWS SDK2 to Authenticate and Get a Session Token

In this blog, we will explore how to use AWS SDK2 to authenticate with AWS services and obtain a session token. We will cover the necessary maven setup, provide code examples, and explain the process step-by-step.

Maven setup

To get started, we need to set up our Maven project to include the necessary dependencies. Open your project’s pom.xml file and add the following dependencies:

<dependencies>
    <!-- AWS SDK2 -->
    <dependency>
        <groupId>software.amazon.awssdk</groupId>
        <artifactId>aws-sdk-java</artifactId>
        <version>2.16.0</version>
    </dependency>
</dependencies>

This will ensure that we have the latest version of the AWS SDK2 included in our project.

Code Examples

Now let’s look at some code examples to authenticate and get a session token using the AWS SDK2.

1. Basic Authentication

import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;

public class BasicAuthenticationExample {

    public static void main(String[] args) {
        // Provide your AWS access key and secret key
        String accessKey = "YOUR_ACCESS_KEY";
        String secretKey = "YOUR_SECRET_KEY";

        // Create credentials using the provided keys
        AwsCredentialsProvider credentialsProvider = StaticCredentialsProvider.create(
                AwsBasicCredentials.create(accessKey, secretKey));

        // Set the desired region
        Region region = Region.US_EAST_1;

        // Now you can use the credentials provider and region to interact with AWS services
        // ...
    }
}

In the above example, we create an AwsCredentialsProvider using the AWS access key and secret key. We then set the desired region to interact with AWS services.

2. SSO-based Authentication

If you are using AWS Single Sign-On (SSO), you can authenticate and get a session token using the AWS SDK2 as follows:

import software.amazon.awssdk.auth.credentials.SsoCredentialsProvider;
import software.amazon.awssdk.auth.credentials.SsoProfileCredentialsProvider;
import software.amazon.awssdk.auth.credentials.SsoTokenResponse;
import software.amazon.awssdk.profiles.Profile;
import software.amazon.awssdk.regions.Region;

import java.nio.file.Paths;

public class SSOAuthenticationExample {

    public static void main(String[] args) {
        // Provide the path to the SSO configuration file
        String ssoConfigFilePath = "PATH_TO_SSO_CONFIG_FILE";

        // Provide the SSO start URL and region
        String startUrl = "SSO_START_URL";
        Region region = Region.US_WEST_2;

        // Set the SSO profile and credentials provider
        Profile ssoProfile = Profile.builder().name("ssoProfile").source("sso")
                .build();

        SsoCredentialsProvider ssoCredentialsProvider = SsoProfileCredentialsProvider.builder()
                .profile(ssoProfile)
                .ssoConfigurationProvider(() -> Paths.get(ssoConfigFilePath))
                .defaultRegion(region)
                .build();

        // Get the token response containing the session token
        SsoTokenResponse tokenResponse = ssoCredentialsProvider.resolveCredentials();

        // Use the session token for authentication
        // ...
    }
}

In the above example, we create an SsoCredentialsProvider using the SSO profile, SSO configuration file path, start URL, and region. We then retrieve the session token from the SsoTokenResponse and use it for authentication.

3. Assume Role-based Authentication

If you need to assume an AWS IAM role to authenticate and get a session token, you can use the following code:

import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
import software.amazon.awssdk.auth.credentials.StsAssumeRoleCredentialsProvider;
import software.amazon.awssdk.regions.Region;

public class AssumeRoleAuthenticationExample {

    public static void main(String[] args) {
        // Provide the ARN of the role to assume
        String roleArn = "ROLE_ARN";
        
        // Provide the session name and region
        String sessionName = "SESSION_NAME";
        Region region = Region.US_WEST_2;
        
        // Set the duration of the assumed role in seconds
        int roleDurationSeconds = 3600;

        // Create the role credentials provider
        StsAssumeRoleCredentialsProvider roleCredentialsProvider = StsAssumeRoleCredentialsProvider.builder()
                .roleArn(roleArn)
                .roleSessionName(sessionName)
                .durationSeconds(roleDurationSeconds)
                .build();

        // Get the assumed role credentials
        AwsCredentials assumedRoleCredentials = roleCredentialsProvider.resolveCredentials();

        // Use the assumed role credentials for authentication
        // ...
    }
}

In the above example, we create an StsAssumeRoleCredentialsProvider using the role ARN, session name, duration, and region. We then obtain the assumed role credentials and use them for authentication.

Conclusion

In this blog post, we have learned how to use AWS SDK2 to authenticate and obtain a session token. We covered the necessary maven setup to include the SDK in our project and provided code examples for basic authentication, SSO-based authentication, and assume role-based authentication. By following these examples, you can easily authenticate and access AWS services using the AWS SDK2.