Example usage for com.amazonaws.services.securitytoken.model Credentials getSessionToken

List of usage examples for com.amazonaws.services.securitytoken.model Credentials getSessionToken

Introduction

In this page you can find the example usage for com.amazonaws.services.securitytoken.model Credentials getSessionToken.

Prototype


public String getSessionToken() 

Source Link

Document

The token that users must pass to the service API to use the temporary credentials.

Usage

From source file:com.netflix.simianarmy.aws.STSAssumeRoleSessionCredentialsProvider.java

License:Apache License

/**
 * Starts a new session by sending a request to the AWS Security Token
 * Service (STS) to assume a Role using the long lived AWS credentials. This
 * class then vends the short lived session credentials for the assumed Role
 * sent back from STS.//from   w ww .  j  a v a2 s . c  o  m
 */
private void startSession() {
    AssumeRoleResult assumeRoleResult = securityTokenService
            .assumeRole(new AssumeRoleRequest().withRoleArn(roleArn)
                    .withDurationSeconds(DEFAULT_DURATION_SECONDS).withRoleSessionName("SimianArmy"));
    Credentials stsCredentials = assumeRoleResult.getCredentials();
    sessionCredentials = new BasicSessionCredentials(stsCredentials.getAccessKeyId(),
            stsCredentials.getSecretAccessKey(), stsCredentials.getSessionToken());
    sessionCredentialsExpiration = stsCredentials.getExpiration();
}

From source file:com.yahoo.athenz.zts.store.CloudStore.java

License:Apache License

public AWSTemporaryCredentials assumeAWSRole(String account, String roleName, String principal) {

    if (!awsEnabled) {
        throw new ResourceException(ResourceException.INTERNAL_SERVER_ERROR, "AWS Support not enabled");
    }/*  ww w.  ja va  2s .co m*/

    AssumeRoleRequest req = getAssumeRoleRequest(account, roleName, principal);

    AWSTemporaryCredentials tempCreds;
    try {
        AWSSecurityTokenServiceClient client = getTokenServiceClient();
        AssumeRoleResult res = client.assumeRole(req);

        Credentials awsCreds = res.getCredentials();
        tempCreds = new AWSTemporaryCredentials().setAccessKeyId(awsCreds.getAccessKeyId())
                .setSecretAccessKey(awsCreds.getSecretAccessKey()).setSessionToken(awsCreds.getSessionToken())
                .setExpiration(Timestamp.fromMillis(awsCreds.getExpiration().getTime()));

    } catch (Exception ex) {
        LOGGER.error("CloudStore: assumeAWSRole - unable to assume role: " + ex.getMessage());
        return null;
    }

    return tempCreds;
}

From source file:com.yahoo.athenz.zts.ZTSClient.java

License:Apache License

String getAWSLambdaAttestationData(final String athenzService, final String account) {

    AWSAttestationData data = new AWSAttestationData();
    data.setRole(athenzService);//from w  w  w.  ja v  a  2 s . co m

    Credentials awsCreds = assumeAWSRole(account, athenzService);
    data.setAccess(awsCreds.getAccessKeyId());
    data.setSecret(awsCreds.getSecretAccessKey());
    data.setToken(awsCreds.getSessionToken());

    ObjectMapper mapper = new ObjectMapper();
    String jsonData = null;
    try {
        jsonData = mapper.writeValueAsString(data);
    } catch (JsonProcessingException ex) {
        LOG.error("Unable to generate attestation json data: {}", ex.getMessage());
    }

    return jsonData;
}

From source file:de.is24.aws.instancemetadataserver.SecurityCredentialsController.java

License:Apache License

private Map<String, String> asJson(Credentials credentials) {
    Map<String, String> json = new HashMap<String, String>();
    json.put("AccessKeyId", credentials.getAccessKeyId());
    json.put("SecretAccessKey", credentials.getSecretAccessKey());
    json.put("Token", credentials.getSessionToken());
    json.put("Expiration", df.format(credentials.getExpiration()));
    json.put("Code", "Success");
    json.put("Type", "AWS-HMAC");

    return json;//  ww w .  j  a v  a 2s.  c o  m
}

From source file:iit.edu.supadyay.s3.S3upload.java

/**
 *
 * @return// w  ww  .  j ava  2 s. com
 */
public static AWSCredentials getCredentials() {
    AWSSecurityTokenServiceClient stsClient = new AWSSecurityTokenServiceClient(
            new ProfileCredentialsProvider());

    //
    // Manually start a session.
    GetSessionTokenRequest getSessionTokenRequest = new GetSessionTokenRequest();
    // Following duration can be set only if temporary credentials are requested by an IAM user.
    getSessionTokenRequest.setDurationSeconds(7200);

    GetSessionTokenResult sessionTokenResult = stsClient.getSessionToken(getSessionTokenRequest);
    Credentials sessionCredentials = sessionTokenResult.getCredentials();

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

    return basicSessionCredentials;

}

From source file:io.fineo.client.auth.CognitoCredentialsProvider.java

License:Open Source License

/**
 * Gets the session credentials from Amazon Cognito.
 *///from www  .  j a v a  2 s . c  om
private void populateCredentialsWithCognito(String token) {

    // For Cognito-authenticated identities token will always be null, but
    // for developer-authenticated identities, refresh() may return a token
    // that the the developer backend has received from Cognito and we have
    // to send back in our request.
    Map<String, String> logins;
    if (token != null && !token.isEmpty()) {
        logins = new HashMap<String, String>();
        logins.put("cognito-identity.amazonaws.com", token);
    } else {
        logins = getLogins();
    }

    GetCredentialsForIdentityRequest request = new GetCredentialsForIdentityRequest()
            .withIdentityId(getIdentityId()).withLogins(logins).withCustomRoleArn(customRoleArn);

    GetCredentialsForIdentityResult result = null;

    try {
        result = cib.getCredentialsForIdentity(request);
    } catch (ResourceNotFoundException rnfe) {
        // If the identity id or identity pool is non-existant, this is
        // thrown
        result = retryGetCredentialsForIdentity();
    } catch (AmazonServiceException ase) {
        // If it's a corrupt id, then a validation exception is thrown
        if (ase.getErrorCode().equals("ValidationException")) {
            result = retryGetCredentialsForIdentity();
        } else {
            throw ase;
        }
    }

    com.amazonaws.services.cognitoidentity.model.Credentials credentials = result.getCredentials();
    sessionCredentials = new BasicSessionCredentials(credentials.getAccessKeyId(), credentials.getSecretKey(),
            credentials.getSessionToken());
    sessionCredentialsExpiration = credentials.getExpiration();

    if (!result.getIdentityId().equals(getIdentityId())) {
        setIdentityId(result.getIdentityId());
    }

}

From source file:io.fineo.client.auth.CognitoCredentialsProvider.java

License:Open Source License

/**
 * Gets the session credentials by requesting an OpenId Connect token from
 * Amazon Cognito and then trading it with AWS Secure Token Service for the
 * short lived session credentials./*from   ww  w  . j av a 2s .c  o  m*/
 */
private void populateCredentialsWithSts(String token) {

    boolean isAuthenticated = identityProvider.isAuthenticated();
    String roleArn = (isAuthenticated) ? authRoleArn : unauthRoleArn;

    AssumeRoleWithWebIdentityRequest sessionTokenRequest = new AssumeRoleWithWebIdentityRequest()
            .withWebIdentityToken(token).withRoleArn(roleArn).withRoleSessionName("ProviderSession")
            .withDurationSeconds(sessionDuration);
    appendUserAgent(sessionTokenRequest, getUserAgent());
    AssumeRoleWithWebIdentityResult sessionTokenResult = securityTokenService
            .assumeRoleWithWebIdentity(sessionTokenRequest);
    Credentials stsCredentials = sessionTokenResult.getCredentials();

    sessionCredentials = new BasicSessionCredentials(stsCredentials.getAccessKeyId(),
            stsCredentials.getSecretAccessKey(), stsCredentials.getSessionToken());
    sessionCredentialsExpiration = stsCredentials.getExpiration();

}

From source file:jetbrains.buildServer.util.amazon.AWSClients.java

License:Apache License

@NotNull
public AWSSessionCredentials createSessionCredentials(@NotNull String iamRoleARN, @Nullable String externalID,
        @NotNull String sessionName, int sessionDuration) throws AWSException {
    final AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest().withRoleArn(iamRoleARN)
            .withRoleSessionName(sessionName).withDurationSeconds(sessionDuration);
    if (StringUtil.isNotEmpty(externalID))
        assumeRoleRequest.setExternalId(externalID);
    try {// www.j a  va  2 s. c  o m
        final Credentials credentials = createSecurityTokenServiceClient().assumeRole(assumeRoleRequest)
                .getCredentials();
        return new BasicSessionCredentials(credentials.getAccessKeyId(), credentials.getSecretAccessKey(),
                credentials.getSessionToken());
    } catch (Exception e) {
        throw new AWSException(e);
    }
}

From source file:org.finra.dm.service.impl.UploadDownloadServiceImpl.java

License:Apache License

/**
 * {@inheritDoc}//from ww  w .j av  a  2 s . co  m
 */
@Override
public UploadSingleInitiationResponse initiateUploadSingle(
        UploadSingleInitiationRequest uploadSingleInitiationRequest) {
    // Validate and trim the request parameters.
    validateUploadSingleInitiationRequest(uploadSingleInitiationRequest);

    // Get the business object format for the specified parameters and make sure it exists.
    BusinessObjectFormatEntity sourceBusinessObjectFormatEntity = dmDaoHelper
            .getBusinessObjectFormatEntity(uploadSingleInitiationRequest.getSourceBusinessObjectFormatKey());

    // Get the target business object format entity for the specified parameters and make sure it exists.
    BusinessObjectFormatEntity targetBusinessObjectFormatEntity = dmDaoHelper
            .getBusinessObjectFormatEntity(uploadSingleInitiationRequest.getTargetBusinessObjectFormatKey());

    // Get the S3 managed "loading dock" storage entity and make sure it exists.
    StorageEntity sourceStorageEntity = dmDaoHelper
            .getStorageEntity(StorageEntity.MANAGED_LOADING_DOCK_STORAGE);

    // Get S3 bucket name for the storage. Please note that since those values are required we pass a "true" flag.
    String s3BucketName = dmDaoHelper.getStorageAttributeValueByName(
            StorageAttributeEntity.ATTRIBUTE_BUCKET_NAME, sourceStorageEntity, true);

    // Get the S3 managed "external" storage entity and make sure it exists.
    StorageEntity targetStorageEntity = dmDaoHelper.getStorageEntity(StorageEntity.MANAGED_EXTERNAL_STORAGE);

    // Generate a random UUID value.
    String uuid = UUID.randomUUID().toString();

    // Create source business object data key with partition value set to the generated UUID.
    BusinessObjectDataKey sourceBusinessObjectDataKey = new BusinessObjectDataKey(
            uploadSingleInitiationRequest.getSourceBusinessObjectFormatKey().getNamespace(),
            uploadSingleInitiationRequest.getSourceBusinessObjectFormatKey().getBusinessObjectDefinitionName(),
            uploadSingleInitiationRequest.getSourceBusinessObjectFormatKey().getBusinessObjectFormatUsage(),
            uploadSingleInitiationRequest.getSourceBusinessObjectFormatKey().getBusinessObjectFormatFileType(),
            uploadSingleInitiationRequest.getSourceBusinessObjectFormatKey().getBusinessObjectFormatVersion(),
            uuid, null, BusinessObjectDataEntity.BUSINESS_OBJECT_DATA_INITIAL_VERSION);

    // Get a file upload specific S3 key prefix based on the generated UUID.
    String storageDirectoryPath = businessObjectDataHelper
            .buildFileUploadS3KeyPrefix(sourceBusinessObjectFormatEntity, sourceBusinessObjectDataKey);
    String storageFilePath = String.format("%s/%s", storageDirectoryPath,
            uploadSingleInitiationRequest.getFile().getFileName());

    // Create a business object data create request.
    BusinessObjectDataCreateRequest sourceBusinessObjectDataCreateRequest = businessObjectDataHelper
            .createBusinessObjectDataCreateRequest(sourceBusinessObjectFormatEntity, uuid,
                    BusinessObjectDataStatusEntity.UPLOADING,
                    uploadSingleInitiationRequest.getBusinessObjectDataAttributes(), sourceStorageEntity,
                    storageDirectoryPath, storageFilePath,
                    uploadSingleInitiationRequest.getFile().getFileSizeBytes(), null);

    // Create a new business object data instance. Set the flag to false, since for the file upload service the file size value is optional.
    BusinessObjectData sourceBusinessObjectData = businessObjectDataHelper
            .createBusinessObjectData(sourceBusinessObjectDataCreateRequest, false);

    // Create a target business object data based on the source business object data and target business object format.
    BusinessObjectDataCreateRequest targetBusinessObjectDataCreateRequest = businessObjectDataHelper
            .createBusinessObjectDataCreateRequest(targetBusinessObjectFormatEntity, uuid,
                    BusinessObjectDataStatusEntity.UPLOADING,
                    uploadSingleInitiationRequest.getBusinessObjectDataAttributes(), targetStorageEntity,
                    storageDirectoryPath, storageFilePath,
                    uploadSingleInitiationRequest.getFile().getFileSizeBytes(), null);

    // Create a target business object data instance. Set the flag to false, since for the file upload service the file size value is optional.
    BusinessObjectData targetBusinessObjectData = businessObjectDataHelper
            .createBusinessObjectData(targetBusinessObjectDataCreateRequest, false);

    // Get decrypted AWS ARN of the role that is required to provide access to S3_MANAGED_LOADING_DOCK storage.
    String awsRoleArn = dmStringHelper
            .getRequiredConfigurationValue(ConfigurationValue.AWS_LOADING_DOCK_UPLOADER_ROLE_ARN);

    // Get expiration interval for the pre-signed URL to be generated.
    Integer awsRoleDurationSeconds = configurationHelper
            .getProperty(ConfigurationValue.AWS_LOADING_DOCK_UPLOADER_ROLE_DURATION_SECS, Integer.class);

    // Get decrypted AWS KMS Loading Dock Key ID value.
    String awsKmsKeyId = dmStringHelper
            .getRequiredConfigurationValue(ConfigurationValue.AWS_KMS_LOADING_DOCK_KEY_ID);

    // Get the temporary security credentials to access S3_MANAGED_STORAGE.
    Credentials assumedSessionCredentials = stsDao.getTemporarySecurityCredentials(awsHelper.getAwsParamsDto(),
            String.valueOf(sourceBusinessObjectData.getId()), awsRoleArn, awsRoleDurationSeconds,
            createUploaderPolicy(s3BucketName, storageFilePath, awsKmsKeyId));

    // Create the response.
    UploadSingleInitiationResponse response = new UploadSingleInitiationResponse();
    response.setSourceBusinessObjectData(sourceBusinessObjectData);
    response.setTargetBusinessObjectData(targetBusinessObjectData);
    response.setFile(uploadSingleInitiationRequest.getFile());
    response.setUuid(uuid);
    response.setAwsAccessKey(assumedSessionCredentials.getAccessKeyId());
    response.setAwsSecretKey(assumedSessionCredentials.getSecretAccessKey());
    response.setAwsSessionToken(assumedSessionCredentials.getSessionToken());
    response.setAwsSessionExpirationTime(
            DmDateUtils.getXMLGregorianCalendarValue(assumedSessionCredentials.getExpiration()));
    response.setAwsKmsKeyId(awsKmsKeyId);

    return response;
}

From source file:org.finra.dm.service.impl.UploadDownloadServiceImpl.java

License:Apache License

/**
 * {@inheritDoc}/*  ww  w. jav a 2  s  .  co m*/
 */
@Override
public DownloadSingleInitiationResponse initiateDownloadSingle(String namespace,
        String businessObjectDefinitionName, String businessObjectFormatUsage,
        String businessObjectFormatFileType, Integer businessObjectFormatVersion, String partitionValue,
        Integer businessObjectDataVersion) {
    // Create the business object data key.
    BusinessObjectDataKey businessObjectDataKey = new BusinessObjectDataKey(namespace,
            businessObjectDefinitionName, businessObjectFormatUsage, businessObjectFormatFileType,
            businessObjectFormatVersion, partitionValue, null, businessObjectDataVersion);

    // Validate the parameters
    dmHelper.validateBusinessObjectDataKey(businessObjectDataKey, true, true, true);

    // Retrieve the persisted business objecty data
    BusinessObjectDataEntity businessObjectDataEntity = dmDaoHelper
            .getBusinessObjectDataEntity(businessObjectDataKey);

    // Make sure the status of the business object data is VALID
    assertBusinessObjectDataStatusEquals(BusinessObjectDataStatusEntity.VALID, businessObjectDataEntity);

    // Get the external storage registered against this data
    // Validate that the storage unit exists
    StorageUnitEntity storageUnitEntity = dmDaoHelper.getStorageUnitEntity(businessObjectDataEntity,
            StorageEntity.MANAGED_EXTERNAL_STORAGE);

    // Validate that the storage unit contains only 1 file
    assertHasOneStorageFile(storageUnitEntity);

    String s3BucketName = dmDaoHelper.getStorageAttributeValueByName(
            StorageAttributeEntity.ATTRIBUTE_BUCKET_NAME, storageUnitEntity.getStorage(), true);
    String s3ObjectKey = storageUnitEntity.getStorageFiles().iterator().next().getPath();

    // Get the temporary credentials
    Credentials downloaderCredentials = getExternalDownloaderCredentials(
            String.valueOf(businessObjectDataEntity.getId()), s3BucketName, s3ObjectKey);

    // Construct and return the response
    DownloadSingleInitiationResponse response = new DownloadSingleInitiationResponse();
    response.setBusinessObjectData(
            businessObjectDataHelper.createBusinessObjectDataFromEntity(businessObjectDataEntity));
    response.setAwsAccessKey(downloaderCredentials.getAccessKeyId());
    response.setAwsSecretKey(downloaderCredentials.getSecretAccessKey());
    response.setAwsSessionToken(downloaderCredentials.getSessionToken());
    response.setAwsSessionExpirationTime(
            DmDateUtils.getXMLGregorianCalendarValue(downloaderCredentials.getExpiration()));
    return response;
}