Menu
Amazon Simple Storage Service
Developer Guide (API Version 2006-03-01)

Making Requests Using Federated User Temporary Credentials - AWS SDK for Java

You can provide temporary security credentials for your federated users and applications (see Making Requests) so they can send authenticated requests to access your AWS resources. When requesting these temporary credentials from the IAM service, you must provide a user name and an IAM policy describing the resource permissions you want to grant. By default, the session duration is one hour. However, if you are requesting temporary credentials using IAM user credentials, you can explicitly set a different duration value when requesting the temporary security credentials for federated users and applications.

Note

To request temporary security credentials for federated users and applications, for added security, you might want to use a dedicated IAM user with only the necessary access permissions. The temporary user you create can never get more permissions than the IAM user who requested the temporary security credentials. For more information, go to AWS Identity and Access Management FAQs .

Making Requests Using Federated User Temporary Security Credentials

1

Create an instance of the AWS Security Token Service client AWSSecurityTokenServiceClient.

2

Start a session by calling the getFederationToken method of the STS client you created in the preceding step.

You will need to provide session information including the user name and an IAM policy that you want to attach to the temporary credentials.

This method returns your temporary security credentials.

3

Package the temporary security credentials in an instance of the BasicSessionCredentials object. You use this object to provide the temporary security credentials to your Amazon S3 client.

4

Create an instance of the AmazonS3Client class by passing the temporary security credentials.

You send requests to Amazon S3 using this client. If you send requests using expired credentials, Amazon S3 returns an error.


The following Java code sample demonstrates the preceding tasks.

// In real applications, the following code is part of your trusted code. It has 
// your security credentials you use to obtain temporary security credentials.
AWSSecurityTokenServiceClient stsClient = 
                        new AWSSecurityTokenServiceClient(new ProfileCredentialsProvider());

GetFederationTokenRequest getFederationTokenRequest = 
                        new GetFederationTokenRequest();
getFederationTokenRequest.setDurationSeconds(7200);
getFederationTokenRequest.setName("User1");

// Define the policy and add to the request.
Policy policy = new Policy();
// Define the policy here.
// Add the policy to the request.
getFederationTokenRequest.setPolicy(policy.toJson());

GetFederationTokenResult federationTokenResult = 
                     stsClient.getFederationToken(getFederationTokenRequest);
Credentials sessionCredentials = federationTokenResult.getCredentials();

// Package the session credentials as a BasicSessionCredentials object 
// for an S3 client object to use.
BasicSessionCredentials basicSessionCredentials = new BasicSessionCredentials(
      sessionCredentials.getAccessKeyId(), 
      sessionCredentials.getSecretAccessKey(), 
      sessionCredentials.getSessionToken());

// The following will be part of your less trusted code. You provide temporary security
// credentials so it can send authenticated requests to Amazon S3. 
// Create an Amazon S3 client by passing in the basicSessionCredentials object.
AmazonS3Client s3 = new AmazonS3Client(basicSessionCredentials);

// Test. For example, send list object keys in a bucket.
ObjectListing objects = s3.listObjects(bucketName);

To set a condition in the policy, create a Condition object and associate it with the policy. The following code sample shows a condition that allows users from a specified IP range to list objects.

Policy policy = new Policy();

// Allow only a specified IP range.
Condition condition = new StringCondition(StringCondition.StringComparisonType.StringLike, 
    ConditionFactory.SOURCE_IP_CONDITION_KEY , "192.168.143.*"); 
        
policy.withStatements(new Statement(Effect.Allow)
    .withActions(S3Actions.ListObjects)
    .withConditions(condition)
    .withResources(new Resource("arn:aws:s3:::"+ bucketName))); 

getFederationTokenRequest.setPolicy(policy.toJson());			

Example

The following Java code example lists keys in the specified bucket. In the code example, you first obtain temporary security credentials for a two-hour session for your federated user (User1) and use them to send authenticated requests to Amazon S3.

When requesting temporary credentials for others, for added security, you use the security credentials of an IAM user who has permissions to request temporary security credentials. You can also limit the access permissions of this IAM user to ensure that the IAM user grants only the minimum application-specific permissions when requesting temporary security credentials. This sample only lists objects in a specific bucket. Therefore, first create an IAM user with the following policy attached.

{
  "Statement":[{
      "Action":["s3:ListBucket",
        "sts:GetFederationToken*"
      ],
      "Effect":"Allow",
      "Resource":"*"
    }
  ]
}

The policy allows the IAM user to request temporary security credentials and access permission only to list your AWS resources. For information about how to create an IAM user, see Creating Your First IAM User and Administrators Group in the IAM User Guide.

You can now use the IAM user security credentials to test the following example. The example sends authenticated request to Amazon S3 using temporary security credentials. The example specifies the following policy when requesting temporary security credentials for the federated user (User1) which restricts access to list objects in a specific bucket (YourBucketName). You must update the policy and provide your own existing bucket name.

{
  "Statement":[
    {
      "Sid":"1",
      "Action":["s3:ListBucket"],
      "Effect":"Allow", 
      "Resource":"arn:aws:s3:::YourBucketName"
    }
  ]
}

You must update the following sample and provide the bucket name that you specified in the preceding federated user access policy.

import java.io.IOException;
import com.amazonaws.auth.BasicSessionCredentials;
import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.auth.policy.Policy;
import com.amazonaws.auth.policy.Resource;
import com.amazonaws.auth.policy.Statement;
import com.amazonaws.auth.policy.Statement.Effect;
import com.amazonaws.auth.policy.actions.S3Actions;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClient;
import com.amazonaws.services.securitytoken.model.Credentials;
import com.amazonaws.services.securitytoken.model.GetFederationTokenRequest;
import com.amazonaws.services.securitytoken.model.GetFederationTokenResult;
import com.amazonaws.services.s3.model.ObjectListing;

public class S3Sample {
	private static String bucketName = "*** Specify bucket name ***";
    public static void main(String[] args) throws IOException {        
        AWSSecurityTokenServiceClient stsClient = 
                        new AWSSecurityTokenServiceClient(new ProfileCredentialsProvider());

        GetFederationTokenRequest getFederationTokenRequest = 
                                         new GetFederationTokenRequest();
        getFederationTokenRequest.setDurationSeconds(7200);
        getFederationTokenRequest.setName("User1");
        
        // Define the policy and add to the request.
        Policy policy = new Policy();
        policy.withStatements(new Statement(Effect.Allow)
            .withActions(S3Actions.ListObjects) 
            .withResources(new Resource("arn:aws:s3:::ExampleBucket"))); 

        getFederationTokenRequest.setPolicy(policy.toJson());
 
        // Get the temporary security credentials.
        GetFederationTokenResult federationTokenResult = 
                        stsClient.getFederationToken(getFederationTokenRequest);
        Credentials sessionCredentials = federationTokenResult.getCredentials();
 
        // Package the session credentials as a BasicSessionCredentials
        // object for an S3 client object to use.
        BasicSessionCredentials basicSessionCredentials = 
              new BasicSessionCredentials(sessionCredentials.getAccessKeyId(), 
        		                          sessionCredentials.getSecretAccessKey(), 
        		                          sessionCredentials.getSessionToken());
        AmazonS3Client s3 = new AmazonS3Client(basicSessionCredentials);

        
        // Test. For example, send ListBucket request using the temporary security credentials. 
        ObjectListing objects = s3.listObjects(bucketName);
        System.out.println("No. of Objects = " + objects.getObjectSummaries().size());
    }
}