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

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

Introduction

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

Prototype


public java.util.Date getExpiration() 

Source Link

Document

The date on which the current credentials expire.

Usage

From source file:com.netflix.eureka.aws.AwsAsgUtil.java

License:Apache License

private AutoScalingGroup retrieveAutoScalingGroupCrossAccount(String asgAccount, String asgName) {
    logger.debug("Getting cross account ASG for asgName: " + asgName + ", asgAccount: " + asgAccount);

    Credentials credentials = stsCredentials.get(asgAccount);

    if (credentials == null || credentials.getExpiration().getTime() < System.currentTimeMillis() + 1000) {
        stsCredentials.put(asgAccount, initializeStsSession(asgAccount));
        credentials = stsCredentials.get(asgAccount);
    }//from w  w w  . j a va2  s  .  c o  m

    ClientConfiguration clientConfiguration = new ClientConfiguration()
            .withConnectionTimeout(serverConfig.getASGQueryTimeoutMs());

    AmazonAutoScaling autoScalingClient = new AmazonAutoScalingClient(
            new BasicSessionCredentials(credentials.getAccessKeyId(), credentials.getSecretAccessKey(),
                    credentials.getSessionToken()),
            clientConfiguration);

    String region = clientConfig.getRegion();
    if (!region.equals("us-east-1")) {
        autoScalingClient.setEndpoint("autoscaling." + region + ".amazonaws.com");
    }

    DescribeAutoScalingGroupsRequest request = new DescribeAutoScalingGroupsRequest()
            .withAutoScalingGroupNames(asgName);
    DescribeAutoScalingGroupsResult result = autoScalingClient.describeAutoScalingGroups(request);
    List<AutoScalingGroup> asgs = result.getAutoScalingGroups();
    if (asgs.isEmpty()) {
        return null;
    } else {
        return asgs.get(0);
    }
}

From source file:com.netflix.eureka.util.AwsAsgUtil.java

License:Apache License

private AutoScalingGroup retrieveAutoScalingGroupCrossAccount(String asgAccount, String asgName) {
    logger.debug("Getting cross account ASG for asgName: " + asgName + ", asgAccount: " + asgAccount);

    Credentials credentials = stsCredentials.get(asgAccount);

    if (credentials == null || credentials.getExpiration().getTime() < System.currentTimeMillis() + 1000) {
        stsCredentials.put(asgAccount, initializeStsSession(asgAccount));
        credentials = stsCredentials.get(asgAccount);
    }/*w ww .  j ava2  s  .  c  o m*/

    ClientConfiguration clientConfiguration = new ClientConfiguration()
            .withConnectionTimeout(eurekaConfig.getASGQueryTimeoutMs());

    AmazonAutoScaling autoScalingClient = new AmazonAutoScalingClient(
            new BasicSessionCredentials(credentials.getAccessKeyId(), credentials.getSecretAccessKey(),
                    credentials.getSessionToken()),
            clientConfiguration);

    String region = DiscoveryManager.getInstance().getEurekaClientConfig().getRegion();
    if (!region.equals("us-east-1")) {
        autoScalingClient.setEndpoint("autoscaling." + region + ".amazonaws.com");
    }

    DescribeAutoScalingGroupsRequest request = new DescribeAutoScalingGroupsRequest()
            .withAutoScalingGroupNames(asgName);
    DescribeAutoScalingGroupsResult result = autoScalingClient.describeAutoScalingGroups(request);
    List<AutoScalingGroup> asgs = result.getAutoScalingGroups();
    if (asgs.isEmpty()) {
        return null;
    } else {
        return asgs.get(0);
    }
}

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.// w  w w .jav  a2s. 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");
    }/*from w  w w  .j  a  v  a2  s.  c  om*/

    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: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;//from   www.jav  a  2 s  .  c o m
}

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

License:Open Source License

/**
 * Gets the session credentials from Amazon Cognito.
 *//*from ww w  .ja  v a  2s .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./*  w  ww.ja va2  s.  co  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:org.finra.dm.service.impl.UploadDownloadServiceImpl.java

License:Apache License

/**
 * {@inheritDoc}//ww w  .j  av  a  2 s.c  o  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}//from  w  w  w  .ja  v a 2s.  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;
}

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

License:Apache License

/**
 * {@inheritDoc}//ww w .j  a v a 2  s. c  o m
 */
@Override
public UploadSingleCredentialExtensionResponse extendUploadSingleCredentials(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);

    // Get the business object data for the key.
    BusinessObjectDataEntity businessObjectDataEntity = dmDaoHelper
            .getBusinessObjectDataEntity(businessObjectDataKey);

    // Ensure the status of the business object data is "uploading" in order to extend credentials.
    if (!(businessObjectDataEntity.getStatus().getCode().equals(BusinessObjectDataStatusEntity.UPLOADING))) {
        throw new IllegalArgumentException(String.format(String.format(
                "Business object data {%s} has a status of \"%s\" and must be \"%s\" to extend "
                        + "credentials.",
                dmHelper.businessObjectDataKeyToString(businessObjectDataKey),
                businessObjectDataEntity.getStatus().getCode(), BusinessObjectDataStatusEntity.UPLOADING)));
    }

    // Get the S3 managed "loading dock" storage entity and make sure it exists.
    StorageEntity storageEntity = 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, storageEntity, true);

    // Get the storage unit entity for this business object data in the S3 managed "loading dock" storage and make sure it exists.
    StorageUnitEntity storageUnitEntity = dmDaoHelper.getStorageUnitEntity(businessObjectDataEntity,
            StorageEntity.MANAGED_LOADING_DOCK_STORAGE);

    // Validate that the storage unit contains exactly one storage file.
    assertHasOneStorageFile(storageUnitEntity);

    // Get the storage file entity.
    StorageFileEntity storageFileEntity = storageUnitEntity.getStorageFiles().iterator().next();

    // Get the storage file path.
    String storageFilePath = storageFileEntity.getPath();

    // 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(businessObjectDataEntity.getId()), awsRoleArn, awsRoleDurationSeconds,
            createUploaderPolicy(s3BucketName, storageFilePath, awsKmsKeyId));

    // Create the response.
    UploadSingleCredentialExtensionResponse response = new UploadSingleCredentialExtensionResponse();
    response.setAwsAccessKey(assumedSessionCredentials.getAccessKeyId());
    response.setAwsSecretKey(assumedSessionCredentials.getSecretAccessKey());
    response.setAwsSessionToken(assumedSessionCredentials.getSessionToken());
    response.setAwsSessionExpirationTime(
            DmDateUtils.getXMLGregorianCalendarValue(assumedSessionCredentials.getExpiration()));

    return response;
}