Search code examples
javaamazon-web-servicessts-securitytokenserviceaws-sts

how to create read only and write only token for specific resource for a file in s3 using AWS STS


I have to generate read only and write only tokens for a file in S3.

What I have tried so far:

  1. create an IAM role with read and write access to the bucket in reference
  2. create an STS client
  3. assume the IAM role created in step #1 by the STS client
  4. generate credentials using sts client

What this does is

  1. lets the user access the file in S3 with the token
  2. but this access is not limited to read only or write only
  3. also if the IAM role has access to more buckets , the token will be accessing all the bucket

Create STS client

AWSSecurityTokenServiceClient sts_client = (AWSSecurityTokenServiceClient) AWSSecurityTokenServiceClientBuilder.standard()
                .withRegion(Regions.DEFAULT_REGION).build();

Create assume role request

AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest()
                .withRoleArn("arn:aws:iam::123456789123:role/iam-role-name")
                .withDurationSeconds(7200)
                .withRoleSessionName("session-role-"+System.currentTimeMillis());

Generate token request

GetSessionTokenRequest session_token_request = new GetSessionTokenRequest();

Generate tokens

GetSessionTokenResult session_token_result = sts_client.getSessionToken(session_token_request);

Create credentials

Credentials session_creds = session_token_result.getCredentials();

Create basic credentials

BasicSessionCredentials sessionCredentials = new BasicSessionCredentials(
            session_creds.getAccessKeyId(),
            session_creds.getSecretAccessKey(),
            session_creds.getSessionToken());

expectation

  1. be able to generate read only and write only tokens
  2. be able to generate path specific tokens
  3. token be limited to only resource in reference and not to all the buckets attached in the IAM role

Solution

  • I found a solutions to this .

    1. make an STS client and assume a given role with permission to all required buckets
    2. create an in line policy and attach to STS client before fetching tokens
    3. make getSessionToken call using STS client

    what is does is :

    1. give access to specific resource limited by path given in in line policy
    2. also it restricts the access to read or write as mentioned in the in line policy