Example usage for com.amazonaws.auth BasicSessionCredentials BasicSessionCredentials

List of usage examples for com.amazonaws.auth BasicSessionCredentials BasicSessionCredentials

Introduction

In this page you can find the example usage for com.amazonaws.auth BasicSessionCredentials BasicSessionCredentials.

Prototype

public BasicSessionCredentials(String awsAccessKey, String awsSecretKey, String sessionToken) 

Source Link

Usage

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

License:Open Source License

/**
 * Gets the session credentials from Amazon Cognito.
 *//*from  w ww  . j a  va2 s.  co m*/
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  a  v a  2  s.c  om*/
 */
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 ava 2s .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.apache.hadoop.fs.s3a.TemporaryAWSCredentialsProvider.java

License:Apache License

public AWSCredentials getCredentials() {
    if (lookupIOE != null) {
        // propagate any initialization problem
        throw new CredentialInitializationException(lookupIOE.toString(), lookupIOE);
    }//from   w ww .j  a v a 2s.  c  o  m
    if (!StringUtils.isEmpty(accessKey) && !StringUtils.isEmpty(secretKey)
            && !StringUtils.isEmpty(sessionToken)) {
        return new BasicSessionCredentials(accessKey, secretKey, sessionToken);
    }
    throw new CredentialInitializationException("Access key, secret key or session token is unset");
}

From source file:org.elasticsearch.discovery.ec2.Ec2ClientSettings.java

License:Apache License

static AWSCredentials loadCredentials(Settings settings) {
    try (SecureString key = ACCESS_KEY_SETTING.get(settings);
            SecureString secret = SECRET_KEY_SETTING.get(settings);
            SecureString sessionToken = SESSION_TOKEN_SETTING.get(settings)) {
        if (key.length() == 0 && secret.length() == 0) {
            if (sessionToken.length() > 0) {
                throw new SettingsException("Setting [{}] is set but [{}] and [{}] are not",
                        SESSION_TOKEN_SETTING.getKey(), ACCESS_KEY_SETTING.getKey(),
                        SECRET_KEY_SETTING.getKey());
            }/*from w ww.  ja va  2 s  .c o  m*/

            logger.debug(
                    "Using either environment variables, system properties or instance profile credentials");
            return null;
        } else {
            if (key.length() == 0) {
                DEPRECATION_LOGGER.deprecated(
                        "Setting [{}] is set but [{}] is not, which will be unsupported in future",
                        SECRET_KEY_SETTING.getKey(), ACCESS_KEY_SETTING.getKey());
            }
            if (secret.length() == 0) {
                DEPRECATION_LOGGER.deprecated(
                        "Setting [{}] is set but [{}] is not, which will be unsupported in future",
                        ACCESS_KEY_SETTING.getKey(), SECRET_KEY_SETTING.getKey());
            }

            final AWSCredentials credentials;
            if (sessionToken.length() == 0) {
                logger.debug("Using basic key/secret credentials");
                credentials = new BasicAWSCredentials(key.toString(), secret.toString());
            } else {
                logger.debug("Using basic session credentials");
                credentials = new BasicSessionCredentials(key.toString(), secret.toString(),
                        sessionToken.toString());
            }
            return credentials;
        }
    }
}

From source file:org.finra.herd.dao.AwsClientFactory.java

License:Apache License

/**
 * Creates a client for accessing Amazon EC2 service.
 *
 * @param awsParamsDto the AWS related parameters DTO that includes optional AWS credentials and proxy information
 *
 * @return the Amazon EC2 client//  ww  w  .  j  av a2 s  . c o m
 */
@Cacheable(DaoSpringModuleConfig.HERD_CACHE_NAME)
public AmazonEC2 getEc2Client(AwsParamsDto awsParamsDto) {
    // Get client configuration.
    ClientConfiguration clientConfiguration = awsHelper.getClientConfiguration(awsParamsDto);

    // If specified, use the AWS credentials passed in.
    if (StringUtils.isNotBlank(awsParamsDto.getAwsAccessKeyId())) {
        return AmazonEC2ClientBuilder.standard()
                .withCredentials(new AWSStaticCredentialsProvider(
                        new BasicSessionCredentials(awsParamsDto.getAwsAccessKeyId(),
                                awsParamsDto.getAwsSecretKey(), awsParamsDto.getSessionToken())))
                .withClientConfiguration(clientConfiguration).withRegion(awsParamsDto.getAwsRegionName())
                .build();
    }
    // Otherwise, use the default AWS credentials provider chain.
    else {
        return AmazonEC2ClientBuilder.standard().withClientConfiguration(clientConfiguration)
                .withRegion(awsParamsDto.getAwsRegionName()).build();
    }
}

From source file:org.finra.herd.dao.AwsClientFactory.java

License:Apache License

/**
 * Creates a client for accessing Amazon EMR service.
 *
 * @param awsParamsDto the AWS related parameters DTO that includes optional AWS credentials and proxy information
 *
 * @return the Amazon EMR client//ww w.  ja v  a 2 s . com
 */
@Cacheable(DaoSpringModuleConfig.HERD_CACHE_NAME)
public AmazonElasticMapReduce getEmrClient(AwsParamsDto awsParamsDto) {
    // Get client configuration.
    ClientConfiguration clientConfiguration = awsHelper.getClientConfiguration(awsParamsDto);

    // If specified, use the AWS credentials passed in.
    if (StringUtils.isNotBlank(awsParamsDto.getAwsAccessKeyId())) {
        return AmazonElasticMapReduceClientBuilder.standard()
                .withCredentials(new AWSStaticCredentialsProvider(
                        new BasicSessionCredentials(awsParamsDto.getAwsAccessKeyId(),
                                awsParamsDto.getAwsSecretKey(), awsParamsDto.getSessionToken())))
                .withClientConfiguration(clientConfiguration).withRegion(awsParamsDto.getAwsRegionName())
                .build();
    }
    // Otherwise, use the default AWS credentials provider chain.
    else {
        return AmazonElasticMapReduceClientBuilder.standard().withClientConfiguration(clientConfiguration)
                .withRegion(awsParamsDto.getAwsRegionName()).build();
    }
}

From source file:org.finra.herd.dao.impl.S3DaoImpl.java

License:Apache License

/**
 * Gets a new S3 client based on the specified parameters. The HTTP proxy information will be added if the host and port are specified in the parameters.
 *
 * @param params the parameters.//from  w  w  w  .  j  ava  2 s  .c  o  m
 *
 * @return the Amazon S3 client.
 */
private AmazonS3Client getAmazonS3(S3FileTransferRequestParamsDto params) {
    AmazonS3Client amazonS3Client;

    ClientConfiguration clientConfiguration = new ClientConfiguration()
            .withRetryPolicy(retryPolicyFactory.getRetryPolicy());

    // Set the proxy configuration, if proxy is specified.
    if (StringUtils.isNotBlank(params.getHttpProxyHost()) && params.getHttpProxyPort() != null) {
        clientConfiguration.setProxyHost(params.getHttpProxyHost());
        clientConfiguration.setProxyPort(params.getHttpProxyPort());
    }

    // Sign all S3 API's with V4 signing.
    // AmazonS3Client.upgradeToSigV4 already has some scenarios where it will "upgrade" the signing approach to use V4 if not already present (e.g.
    // GetObjectRequest and KMS PutObjectRequest), but setting it here (especially when KMS is used) will ensure it isn't missed when required (e.g.
    // copying objects between KMS encrypted buckets). Otherwise, AWS will return a bad request error and retry which isn't desirable.
    clientConfiguration.setSignerOverride(SIGNER_OVERRIDE_V4);

    // Set the optional socket timeout, if configured.
    if (params.getSocketTimeout() != null) {
        clientConfiguration.setSocketTimeout(params.getSocketTimeout());
    }

    // Create an S3 client using passed in credentials and HTTP proxy information.
    if (StringUtils.isNotBlank(params.getAwsAccessKeyId()) && StringUtils.isNotBlank(params.getAwsSecretKey())
            && StringUtils.isNotBlank(params.getSessionToken())) {
        // Create an S3 client using basic session credentials.
        amazonS3Client = new AmazonS3Client(new BasicSessionCredentials(params.getAwsAccessKeyId(),
                params.getAwsSecretKey(), params.getSessionToken()), clientConfiguration);
    } else {
        // Create an S3 client using AWS credentials provider.
        amazonS3Client = new AmazonS3Client(getAWSCredentialsProvider(params), clientConfiguration);
    }

    // Set the optional endpoint, if specified.
    if (StringUtils.isNotBlank(params.getS3Endpoint())) {
        LOGGER.info("Configured S3 Endpoint: " + params.getS3Endpoint());
        amazonS3Client.setEndpoint(params.getS3Endpoint());
    }

    // Return the newly created client.
    return amazonS3Client;
}

From source file:org.jooby.internal.aws.ConfigCredentialsProvider.java

License:Apache License

@Override
public AWSCredentials getCredentials() {
    if (sessionToken != null) {
        return new BasicSessionCredentials(accessKey, secretKey, sessionToken);
    }//w  ww .  j  ava2  s .c  om
    return new BasicAWSCredentials(accessKey, secretKey);
}

From source file:org.jooby.internal.aws.CredentialsFactory.java

License:Apache License

private static void applicationCredentials(Config conf, String serviceName,
        Consumer<AWSCredentialsProvider> consumer) {
    String accessKey = find(conf, "aws." + serviceName + "." + ACCESS_KEY, "aws." + ACCESS_KEY);
    if (accessKey != null) {
        String secretKey = find(conf, "aws." + serviceName + "." + SECRET_KEY, "aws." + SECRET_KEY);
        String sessionToken = find(conf, "aws." + serviceName + "." + SESSION_TOKEN, "aws." + SESSION_TOKEN);
        AWSCredentials credentials = sessionToken == null ? new BasicAWSCredentials(accessKey, secretKey)
                : new BasicSessionCredentials(accessKey, secretKey, sessionToken);
        consumer.accept(new AWSStaticCredentialsProvider(credentials));
    }//from www .j  ava  2  s  .  co m
}