

# Using AWS SDK for PHP Version 3 credential providers
<a name="guide_credentials"></a>

For reference information on available credentials mechanisms for the AWS SDKs, see [Credentials and access](https://docs.aws.amazon.com/sdkref/latest/guide/access.html) in the *AWS SDKs and Tools Reference Guide*.

**Important**  
For security, we *strongly recommend* that you do **not** use the root account for AWS access. Always refer to the [Security best practices in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html) in the *IAM User Guide* for the latest security recommendations.

The role of a credentials provider in the AWS SDK for PHP Version 3 is to source and supply credentials to the SDK's AWS service clients. The SDK uses the credentials it sources to authenticate with the service by cryptographically signing each request. Credentials usually consist of access keys—an access key ID and a secret access key together. 

When you use temporary credentials, such as when you [set up IAM Identity Center authentication](credentials.md#use-idc-for-auth) or configure your runtime to [assume an IAM role](assumerole-provider.md), a session token is added to the access keys, providing time-limited access to AWS resources.

## What is a credential provider in the AWS SDK for PHP Version 3?
<a name="cred-provider-defn-php"></a>

A credential provider is a function that returns a `GuzzleHttp\Promise\PromiseInterface` that is fulfilled with an `Aws\Credentials\CredentialsInterface` instance or rejected with an `Aws\Exception\CredentialsException`. The [SDK provides several implementations](built-in-providers-in-the-sdk.md) of credential provider functions or you can [implement your own](creating-a-custom-provider.md) custom logic for creating credentials or to optimize credential loading.

Credential providers are passed into the `credentials` client constructor option. Credential providers are asynchronous, which forces them to be lazily evaluated each time an API operation is invoked. As such, passing in a credential provider function to an SDK client constructor doesn’t immediately validate the credentials. If the credential provider doesn’t return a credentials object, an API operation will be rejected with an `Aws\Exception\CredentialsException`.

```
use Aws\Credentials\CredentialProvider;
use Aws\S3\S3Client;

// Use the ECS credential provider. 
$provider = CredentialProvider::ecsCredentials();
// Be sure to memoize the credentials.
$memoizedProvider = CredentialProvider::memoize($provider);

// Pass the provider to the client
$client = new S3Client([
    'region'      => 'us-west-2',
    'version'     => '2006-03-01',
    'credentials' => $memoizedProvider
]);
```

# Understanding the default credential provider chain in the AWS SDK for PHP Version 3
<a name="guide_credentials_default_chain"></a>

The default credential provider chain is made up of a series of built-in credential providers that the SDK invokes. It is implemented by the [defaultProvider](defaultprovider-provider.md) credential provider function with no parameters. After valid credentials are found, the search is stopped.

The AWS SDK for PHP executes credential providers in the following order:
+ [**`env` provider**](env-provider.md) - the SDK searches for [AWS access keys that have been set as environment variables](https://docs.aws.amazon.com/sdkref/latest/guide/feature-static-credentials.html).
+ [**`assumeRoleWithWebIdentityCredentialProvider` provider**](assume-role-with-web-identity-provider.md) - The SDK searches for IAM role and web identity token file settings.
+ At this point in the chain, the SDK looks for configuration in the shared AWS `config` and `credentials` files. The SDK looks for configuration under the "default" profile, but if the `AWS_PROFILE` environment variable is set, the SDK uses its named profile value.
  +  [**`sso` provider**](sso-provider.md) - The SDK looks for [IAM Identity Center configuration settings](https://docs.aws.amazon.com/sdkref/latest/guide/feature-sso-credentials.html#sso-token-config) in the shared `config` file.
  +  [**`login provider` **](login-provider.md) - The SDK looks for AWS console login session configuration settings in the shared `config` file.
  + [**`process` provider **](process-provider.md) - The SDK looks for the `credential_process` setting in the shared `credentials` file.
  + [**`ini` provider**](ini-provider.md) - The SDK looks for the AWS credentials or IAM role information in the shared `credentials` file.
  + [**`process` provider**](process-provider.md) - The SDK looks for the `credential_process` setting in the shared `config` file.
  + [**`ini` provider**](ini-provider.md) - The SDK looks for the AWS credentials or IAM role information in the shared `config` file.
+ [**`ecsCredentials` provider**](ecscredentials-provider.md) - The SDK looks for the environment variables `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI `or `AWS_CONTAINER_CREDENTIALS_FULL_URI` that provide information to acquire temporary credentials.
+ [**`instanceProfile` provider**](instanceprofile-provider.md) - The SDK uses the EC2 Instance Metadata service to get the IAM role specified in the instance profile. Using the role information, the SDK acquires temporary credentials.

**Note**  
The result of the default provider is automatically memoized.

You can review the code for the chain in the GitHub [source code](https://github.com/aws/aws-sdk-php/blob/0a99dab427f0a1c082775301141aeac3558691ad/src/Credentials/CredentialProvider.php#L77).

# Built-in credential providers in the AWS SDK for PHP Version 3
<a name="built-in-providers-in-the-sdk"></a>

The SDK provides several built-in credential providers that you can use individually or combine in a [custom credential provider chain](chaining-providers.md). 

When you specify a credential provider during service client creation, the SDK attempts to load credentials by using only the specified credential provider. It does not use the [default credential provider chain](guide_credentials_default_chain.md). If you know that you want a service client to use the `instanceProfile` provider, you can short-circuit the default chain by specifying the `instanceProfile` provider in the service client constructor:

```
use Aws\Credentials\CredentialProvider;
use Aws\S3\S3Client;

$provider = CredentialProvider::instanceProfile();
// Be sure to memoize the credentials
$memoizedProvider = CredentialProvider::memoize($provider);

$client = new S3Client([
    'region'      => 'us-west-2',
    'credentials' => $memoizedProvider  // The default credential provider chain is not used.
]);
```

**Important**  
Credential providers are invoked every time an API operation is performed. If loading credentials is an expensive task (e.g., loading from disk or a network resource), or if credentials are not cached by your provider, consider wrapping your credential provider in an `Aws\Credentials\CredentialProvider::memoize` function. The default credential provider used by the SDK is automatically memoized.

**Topics**
+ [`login` provider in the SDK for PHP](login-provider.md)
+ [`assumeRole` provider in the SDK for PHP](assumerole-provider.md)
+ [`sso` provider in the SDK for PHP](sso-provider.md)
+ [`defaultProvider` provider in the SDK for PHP](defaultprovider-provider.md)
+ [`ecsCredentials` provider in the SDK for PHP](ecscredentials-provider.md)
+ [`env` provider in the SDK for PHP](env-provider.md)
+ [`assumeRoleWithWebIdentityCredentialProvider` provider in the SDK for PHP](assume-role-with-web-identity-provider.md)
+ [`ini` provider in the SDK for PHP](ini-provider.md)
+ [`process` provider in the SDK for PHP](process-provider.md)
+ [`instanceProfile` provider in the SDK for PHP](instanceprofile-provider.md)

# `login` provider in the SDK for PHP
<a name="login-provider"></a>

`Aws\Credentials\CredentialProvider::login` attempts to load credentials configured by a browser-based login session facilitated by tools like the AWS CLI. After authentication, AWS generates temporary credentials that work across local AWS SDKs and tools.

With this process, you can authenticate using root credentials created during initial account set up, an IAM user, or a federated identity from your identity provider, and the AWS SDK for PHP automatically manage the temporary credentials for you. This approach enhances security by eliminating the need to store long-term credentials locally.

When you run the `aws login` command, you can select from your active console sessions, or sign in through the browser-based authentication flow and this will automatically generate temporary credentials. The AWS SDK for PHP will automatically refresh these credentials, using the Sign-In service, for up to 12 hours.

The login provider attempts to load the access token generated by the previously mentioned login session workflow, based on the profile provided. If no profile is provided when calling the provider, it will attempt to resolve a profile by first checking the `AWS_PROFILE` environment variable, before falling back to the profile `default`. In-code configuration can be passed to the provider, where it will look for a `region` value for the Sign-In service client used for refreshing credentials. If no region is provided in the configuration array, the provider will attempt to resolve a region by checking the `AWS_REGION` environment variable, then a region value set in the resolved profile. If no region can be found, the provider will return a rejected promise with instructions on how to configure a region.

The provider is called as a part of the default chain and can be called directly.

```
use Aws\Credentials\CredentialProvider;
use Aws\S3\S3Client;

$provider = CredentialProvider::login(<profile_name>, ['region' => <region>]);
// Cache the results in a memoize function to avoid loading and parsing
// the ini file on every API operation
$provider = CredentialProvider::memoize($provider);

$client = new S3Client([
    'region' => 'us-west-2',
    'credentials' => $provider
]);
```

By default, if no credentials configuration is provided on the service client you wish to use, this provider will be called as a part of the `defaultProvider()` credentials chain. In this scenario, the region of the service client is automatically passed to the `login()` provider. Also in this scenario, the profile value passed to the login provider will be resolved by checking the `AWS_PROFILE` environment variable, before falling back to the profile `default`.

# `assumeRole` provider in the SDK for PHP
<a name="assumerole-provider"></a>

If you use `Aws\Credentials\AssumeRoleCredentialProvider` to create credentials by assuming a role, you need to provide `'client'` information with an `StsClient` object and `'assume_role_params'` details, as shown.

**Note**  
To avoid unnecessarily fetching AWS STS credentials on every API operation, you can use the `memoize` function to handle automatically refreshing the credentials when they expire. See the following code for an example.

```
use Aws\Credentials\CredentialProvider;
use Aws\Credentials\InstanceProfileProvider;
use Aws\Credentials\AssumeRoleCredentialProvider;
use Aws\S3\S3Client;
use Aws\Sts\StsClient;

// Passing Aws\Credentials\AssumeRoleCredentialProvider options directly
$profile = new InstanceProfileProvider();
$ARN = "arn:aws:iam::123456789012:role/xaccounts3access";
$sessionName = "s3-access-example";

$assumeRoleCredentials = new AssumeRoleCredentialProvider([
    'client' => new StsClient([
        'region' => 'us-east-2',
        'version' => '2011-06-15',
        'credentials' => $profile
    ]),
    'assume_role_params' => [
        'RoleArn' => $ARN,
        'RoleSessionName' => $sessionName,
    ],
]);

// To avoid unnecessarily fetching STS credentials on every API operation,
// the memoize function handles automatically refreshing the credentials when they expire
$provider = CredentialProvider::memoize($assumeRoleCredentials);

$client = new S3Client([
    'region'      => 'us-east-2',
    'version'     => '2006-03-01',
    'credentials' => $provider
]);
```

For more information regarding `'assume_role_params'`, see [AssumeRole](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sts-2011-06-15.html#assumerole).

# `sso` provider in the SDK for PHP
<a name="sso-provider"></a>

`Aws\Credentials\CredentialProvider::sso` is the single sign-on credential provider. This provider is also known as the AWS IAM Identity Center credential provider.

```
use Aws\Credentials\CredentialProvider;
use Aws\S3\S3Client;

$credentials = CredentialProvider::sso('profile default');

$s3 = new Aws\S3\S3Client([
    'version'     => 'latest',
    'region'      => 'us-west-2',
    'credentials' => $credentials
]);
```

If you use a named profile, substitute the name of your profile for ‘`default`’ in the previous example. To learn more about setting up named profiles, see [Shared `config` and `credentials` files](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html) in the *AWS SDKs and Tools Reference Guide*. Alternatively, you can use the [https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html#file-format-profile](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html#file-format-profile) environment variable to specify which profile's settings to use. 

To understand more how the IAM Identity Center provider works, see [Understand IAM Identity Center authentication](https://docs.aws.amazon.com/sdkref/latest/guide/understanding-sso.html) in the *AWS SDKs and Tools Reference Guide*.

# `defaultProvider` provider in the SDK for PHP
<a name="defaultprovider-provider"></a>

 `Aws\Credentials\CredentialProvider::defaultProvider` is the default credential provider and is also called the [default credential provider chain](guide_credentials_default_chain.md). This provider is used if you omit a `credentials` option when creating a client. For example, if you create an S3Client as shown in the following snippet, the SDK uses the default provider:

```
$client = new S3Client([
    'region' => 'us-west-2'
]);
```

You can also use the defaultProvider in code if you want to supply parameters to specific credential providers in the chain. For example the following example provides custom connection timeout and retry settings if the `ecsCredentials` provider function is used.

```
use Aws\Credentials\CredentialProvider;
use Aws\S3\S3Client;

$provider = CredentialProvider::defaultProvider([
    'timeout' => '1.5',
    'retries' => 5
]);

$client = new S3Client([
    'region' => 'us-west-2',
    'credentials' => $provider
]);
```

# `ecsCredentials` provider in the SDK for PHP
<a name="ecscredentials-provider"></a>

 `Aws\Credentials\CredentialProvider::ecsCredentials` attempts to load credentials by a `GET` request, whose URI is specified by the environment variable `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI` in the container.

```
use Aws\Credentials\CredentialProvider;
use Aws\S3\S3Client;

$provider = CredentialProvider::ecsCredentials();
// Be sure to memoize the credentials
$memoizedProvider = CredentialProvider::memoize($provider);

$client = new S3Client([
    'region'      => 'us-west-2',
    'version'     => '2006-03-01',
    'credentials' => $memoizedProvider
]);
```

# `env` provider in the SDK for PHP
<a name="env-provider"></a>

Using environment variables to contain your credentials prevents you from accidentally sharing your AWS secret access key. We recommend that you never add your AWS access keys directly to the client in any production files.

To authenticate to Amazon Web Services, the SDK first checks for credentials in your environment variables. The SDK uses the `getenv()` function to look for the `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_SESSION_TOKEN` environment variables. These credentials are referred to as environment credentials. For instructions on how to obtain these values, see [Authenticate using short-term credentials](https://docs.aws.amazon.com/sdkref/latest/guide/access-temp-idc.html) in the *AWS SDKs and Tools Reference Guide*.

If you’re hosting your application on [AWS Elastic Beanstalk](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_PHP_eb.html), you can set the `AWS_ACCESS_KEY_ID`, `AWS_SECRET_KEY`, and `AWS_SESSION_TOKEN` environment variables [through the AWS Elastic Beanstalk console](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environments-cfg-softwaresettings.html#environments-cfg-softwaresettings-console) so that the SDK can use those credentials automatically.

For more information on how to set environment variables, see [Environment variables support](https://docs.aws.amazon.com/sdkref/latest/guide/environment-variables.html) in the *AWS SDKs and Tools Reference Guide*. Also, for a list of all environment variables supported by most AWS SDKs, see [Environment variables list](https://docs.aws.amazon.com/sdkref/latest/guide/settings-reference.html#EVarSettings).

You can also set the environment variables in the command line, as shown here.

 **Linux** 

```
$ export AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE
   # The access key for your AWS account.
$ export AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
   # The secret access key for your AWS account.
$ export AWS_SESSION_TOKEN=AQoDYXdzEJr...<remainder of security token>
   # The temporary session key for your AWS account. 
   # The AWS_SECURITY_TOKEN environment variable can also be used, but is only supported for backward compatibility purposes.
   # AWS_SESSION_TOKEN is supported by multiple AWS SDKs other than PHP.
```

 **Windows** 

```
C:\> SET  AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE
   # The access key for your AWS account.
C:\> SET  AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
   # The secret access key for your AWS account.
C:\> SET AWS_SESSION_TOKEN=AQoDYXdzEJr...<remainder of security token>
   # The temporary session key for your AWS account. 
   # The AWS_SECURITY_TOKEN environment variable can also be used, but is only supported for backward compatibility purposes.
   # AWS_SESSION_TOKEN is supported by multiple AWS SDKs besides PHP.
```

 `Aws\Credentials\CredentialProvider::env` attempts to load credentials from environment variables.

```
use Aws\Credentials\CredentialProvider;
use Aws\S3\S3Client;

$client = new S3Client([
    'region'      => 'us-west-2',
    'version'     => '2006-03-01',
    'credentials' => CredentialProvider::env()
]);
```

# `assumeRoleWithWebIdentityCredentialProvider` provider in the SDK for PHP
<a name="assume-role-with-web-identity-provider"></a>

 `Aws\Credentials\CredentialProvider::assumeRoleWithWebIdentityCredentialProvider` attempts to load credentials by assuming a role. If the environment variables `AWS_ROLE_ARN` and `AWS_WEB_IDENTITY_TOKEN_FILE` are present, the provider will attempt to assume the role specified at `AWS_ROLE_ARN` using the token on disk at the full path specified in `AWS_WEB_IDENTITY_TOKEN_FILE`. If environment variables are used, the provider will attempt to set the session from the `AWS_ROLE_SESSION_NAME` environment variable.

If environment variables are not set, the provider will use the default profile, or the one set as `AWS_PROFILE`. The provider reads profiles from `~/.aws/credentials` and `~/.aws/config` by default, and can read from profiles specified in the `filename` config option. The provider will assume the role in `role_arn` of the profile, reading a token from the full path set in `web_identity_token_file`. `role_session_name` will be used if set on the profile.

The provider is called as part of the default chain and can be called directly.

```
use Aws\Credentials\CredentialProvider;
use Aws\S3\S3Client;

$provider = CredentialProvider::assumeRoleWithWebIdentityCredentialProvider();
// Cache the results in a memoize function to avoid loading and parsing
// the ini file on every API operation
$provider = CredentialProvider::memoize($provider);

$client = new S3Client([
    'region'      => 'us-west-2',
    'version'     => '2006-03-01',
    'credentials' => $provider
]);
```

By default, this credential provider will inherit the configured region which will be used by the StsClient to assume the role. Optionally, a full StsClient can be provided. Credentials should be set as `false` on any provided StsClient.

```
use Aws\Credentials\CredentialProvider;
use Aws\S3\S3Client;
use Aws\Sts\StsClient;

$stsClient = new StsClient([
    'region'      => 'us-west-2',
    'version'     => 'latest',
    'credentials' => false
])

$provider = CredentialProvider::assumeRoleWithWebIdentityCredentialProvider([
    'stsClient' => $stsClient
]);
// Cache the results in a memoize function to avoid loading and parsing
// the ini file on every API operation
$provider = CredentialProvider::memoize($provider);

$client = new S3Client([
    'region'      => 'us-west-2',
    'version'     => '2006-03-01',
    'credentials' => $provider
]);
```

# `ini` provider in the SDK for PHP
<a name="ini-provider"></a>

 `Aws\Credentials\CredentialProvider::ini` attempts to load credentials from the shared `config` and `credentials` files. By default, the SDK attempts to load the “default” profile from the shared AWS `credentials` file located at `~/.aws/credentials`. If the SDK finds the `AWS_SDK_LOAD_NONDEFAULT_CONFIG` environment variable, it also checks for a "default" profile in the shared AWS `config` file located at `~/.aws/config`.

```
use Aws\Credentials\CredentialProvider;
use Aws\S3\S3Client;

$provider = CredentialProvider::ini();
// Cache the results in a memoize function to avoid loading and parsing
// the ini file on every API operation
$provider = CredentialProvider::memoize($provider);

$client = new S3Client([
    'region'      => 'us-west-2',
    'version'     => '2006-03-01',
    'credentials' => $provider
]);
```

You can use a custom profile or .ini file location by providing arguments to the function that creates the provider.

```
$profile = 'production';
$path = '/full/path/to/credentials.ini';

$provider = CredentialProvider::ini($profile, $path);
$provider = CredentialProvider::memoize($provider);

$client = new S3Client([
    'region'      => 'us-west-2',
    'version'     => '2006-03-01',
    'credentials' => $provider
]);
```

# `process` provider in the SDK for PHP
<a name="process-provider"></a>

 `Aws\Credentials\CredentialProvider::process` attempts to load credentials by executing `credential_process` value that is specified in a profile in a [shared AWS configuration file](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html). 

By default, the SDK attempts to load the “default” profile first from the shared AWS `credentials` file located at `~/.aws/credentials`. If the "default" profile is not found in the shared `credentials` file, the SDK looks in the shared `config` file for the default profile. The following is an example of configuration for the shared `credentials` file.

```
[default]
credential_process = /path/to/file/credential_returning_executable.sh --custom-command custom_parameter
```

The SDK will call the `credential_process` command exactly as given by using PHP's `shell_exec` function and then read JSON data from stdout. The `credential_process` must write credentials to stdout in the following format:

```
{
    "Version": 1,
    "AccessKeyId": "",
    "SecretAccessKey": "",
    "SessionToken": "",
    "Expiration": ""
}
```

 `SessionToken` and `Expiration` are optional. If present, the credentials will be treated as temporary.

```
use Aws\Credentials\CredentialProvider;
use Aws\S3\S3Client;

$provider = CredentialProvider::process();
// Cache the results in a memoize function to avoid loading and parsing
// the ini file on every API operation
$provider = CredentialProvider::memoize($provider);

$client = new S3Client([
    'region'      => 'us-west-2',
    'version'     => '2006-03-01',
    'credentials' => $provider
]);
```

You can use a custom profile or .ini file location by providing arguments to the function that creates the provider.

```
$profile = 'production';
$path = '/full/path/to/credentials.ini';

$provider = CredentialProvider::process($profile, $path);
$provider = CredentialProvider::memoize($provider);

$client = new S3Client([
    'region'      => 'us-west-2',
    'version'     => '2006-03-01',
    'credentials' => $provider
]);
```

# `instanceProfile` provider in the SDK for PHP
<a name="instanceprofile-provider"></a>

 `Aws\Credentials\CredentialProvider::instanceProfile` attempts to load credentials for an IAM role specified in an Amazon EC2 instance profile.

```
use Aws\Credentials\CredentialProvider;
use Aws\S3\S3Client;

$provider = CredentialProvider::instanceProfile();
// Be sure to memoize the credentials
$memoizedProvider = CredentialProvider::memoize($provider);

$client = new S3Client([
    'region'      => 'us-west-2',
    'version'     => '2006-03-01',
    'credentials' => $memoizedProvider
]);
```

By default, the provider retries fetching credentials up to three times. The number of retries can be set with the `retries` option, and disabled entirely by setting the option to `0` as shown in the following code.

```
use Aws\Credentials\CredentialProvider;

$provider = CredentialProvider::instanceProfile([
    'retries' => 0
]);
$memoizedProvider = CredentialProvider::memoize($provider);
```

If the environment variable `AWS_METADATA_SERVICE_NUM_ATTEMPTS` is available, its value takes precedence over the 'retries' option shown previously. 

**Note**  
You can disable this attempt to load from Amazon EC2 instance profiles by setting the `AWS_EC2_METADATA_DISABLED` environment variable to `true`.

# Chaining credential providers in the SDK for PHP
<a name="chaining-providers"></a>

You can chain credential providers by using the `Aws\Credentials\CredentialProvider::chain()` function. This function accepts a variadic number of arguments, each of which are credential provider functions. This function then returns a new function that’s the composition of the provided functions, such that they are invoked one after the other until one of the providers returns a promise that is fulfilled successfully.

The `defaultProvider` uses this composition to check multiple providers before failing. The source of the `defaultProvider` demonstrates the use of the `chain` function.

```
// This function returns a provider
public static function defaultProvider(array $config = [])
{
    // This function is the provider, which is actually the composition
    // of multiple providers. Notice that we are also memoizing the result by
    // default.
    return self::memoize(
        self::chain(
            self::env(),
            self::ini(),
            self::instanceProfile($config)
        )
    );
}
```

# Creating a custom credential provider to use with the SDK for PHP
<a name="creating-a-custom-provider"></a>

Credential providers are simply functions that when invoked return a promise (`GuzzleHttp\Promise\PromiseInterface`) that is fulfilled with an `Aws\Credentials\CredentialsInterface` object or rejected with an `Aws\Exception\CredentialsException`.

A best practice for creating providers is to create a function that is invoked to create the actual credential provider. As an example, here’s the source of the `env` provider (slightly modified for example purposes). Notice that it is a function that returns the actual provider function. This allows you to easily compose credential providers and pass them around as values.

```
use GuzzleHttp\Promise;
use GuzzleHttp\Promise\RejectedPromise;

// This function CREATES a credential provider
public static function env()
{
    // This function IS the credential provider
    return function () {
        // Use credentials from environment variables, if available
        $key = getenv(self::ENV_KEY);
        $secret = getenv(self::ENV_SECRET);
        if ($key && $secret) {
            return Create::promise_for(
                new Credentials($key, $secret, getenv(self::ENV_SESSION))
            );
        }

        $msg = 'Could not find environment variable '
            . 'credentials in ' . self::ENV_KEY . '/' . self::ENV_SECRET;
        return new RejectedPromise(new CredentialsException($msg));
    };
}
```

# Memoizing credentials in the SDK for PHP
<a name="memoizing-credentials"></a>

At times you might need to create a credential provider that remembers the previous return value. This can be useful for performance when loading credentials is an expensive operation or when using the `Aws\Sdk` class to share a credential provider across multiple clients. You can add memoization to a credential provider by wrapping the credential provider function in a `memoize` function.

```
use Aws\Credentials\CredentialProvider;

$provider = CredentialProvider::instanceProfile();
// Wrap the actual provider in a memoize function
$provider = CredentialProvider::memoize($provider);

// Pass the provider into the Sdk class and share the provider
// across multiple clients. Each time a new client is constructed,
// it will use the previously returned credentials as long as
// they haven't yet expired.
$sdk = new Aws\Sdk(['credentials' => $provider]);

$s3 = $sdk->getS3(['region' => 'us-west-2', 'version' => 'latest']);
$ec2 = $sdk->getEc2(['region' => 'us-west-2', 'version' => 'latest']);

assert($s3->getCredentials() === $ec2->getCredentials());
```

When the memoized credentials are expired, the memoize wrapper invokes the wrapped provider in an attempt to refresh the credentials.

# Assume an IAM role using the AWS SDK for PHP Version 3
<a name="guide_credentials_assume_role"></a>

## Using IAM roles for Amazon EC2 instance variable credentials
<a name="instance-profile-credentials"></a>

If you’re running your application on an Amazon EC2 instance, the preferred way to provide credentials to make calls to AWS is to use an [IAM role](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html) to get temporary security credentials.

When you use IAM roles, you don’t need to worry about credential management from your application. They allow an instance to “assume” a role by retrieving temporary credentials from the Amazon EC2 instance’s metadata server.

The temporary credentials, often referred to as **instance profile credentials**, allow access to the actions and resources that the role’s policy allows. Amazon EC2 handles all the legwork of securely authenticating instances to the IAM service to assume the role, and periodically refreshing the retrieved role credentials. This keeps your application secure with almost no work on your part. For a list of the services that accept temporary security credentials, see [AWS services that work with IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-services-that-work-with-iam.html) in the *IAM User Guide*.

**Note**  
To avoid hitting the metadata service every time, you can pass an instance of `Aws\CacheInterface` in as the `'credentials'` option to a client constructor. This lets the SDK use cached instance profile credentials instead. For details, see [Configuration for the AWS SDK for PHP Version 3](guide_configuration.md).

For more information on developing Amazon EC2 applications using the SDKs, see [Using IAM roles for Amazon EC2 instances](https://docs.aws.amazon.com/sdkref/latest/guide/access-iam-roles-for-ec2.html) in the *AWS SDKs and Tools Reference Guide*.

### Create and assign an IAM role to an Amazon EC2 instance
<a name="create-and-assign-an-iam-role-to-an-ec2-instance"></a>

1. Create an IAM client.

    **Imports** 

   ```
   require 'vendor/autoload.php';
   
   use Aws\Iam\IamClient;
   ```

    **Sample Code** 

   ```
   $client = new IamClient([
       'region' => 'us-west-2',
       'version' => '2010-05-08'
   ]);
   ```

1. Create an IAM role with the permissions for the actions and resources you’ll use.

    **Sample Code** 

   ```
   $result = $client->createRole([
       'AssumeRolePolicyDocument' => 'IAM JSON Policy', // REQUIRED
       'Description' => 'Description of Role',
       'RoleName' => 'RoleName', // REQUIRED
   ]);
   ```

1. Create an IAM instance profile and store the Amazon Resource Name (ARN) from the result.
**Note**  
If you use the IAM console instead of the AWS SDK for PHP, the console creates an instance profile automatically and gives it the same name as the role to which it corresponds.  
 **Sample Code**   

   ```
   $IPN = 'InstanceProfileName';
   
   $result = $client->createInstanceProfile([
       'InstanceProfileName' => $IPN ,
   ]);
   
   $ARN = $result['Arn'];
   $InstanceID =  $result['InstanceProfileId'];
   ```

1. Create an Amazon EC2 client.

    **Imports** 

   ```
   require 'vendor/autoload.php';
   
   use Aws\Ec2\Ec2Client;
   ```

    **Sample Code** 

   ```
   $ec2Client = new Ec2Client([
       'region' => 'us-west-2',
       'version' => '2016-11-15',
   ]);
   ```

1. Add the instance profile to a running or stopped Amazon EC2 instance. Use the instance profile name of your IAM role.

    **Sample Code** 

   ```
    $result = $ec2Client->associateIamInstanceProfile([
       'IamInstanceProfile' => [
           'Arn' => $ARN,
           'Name' => $IPN,
       ],
       'InstanceId' => $InstanceID
   ]);
   ```

For more information, see [IAM Roles for Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html) in the *Amazon EC2 User Guide*.

## Using IAM roles for Amazon ECS tasks
<a name="ecs-credentials"></a>

A task in Amazon Elastic Container Service (Amazon ECS) can assume an IAM role to make AWS API calls. This is a strategy for managing credentials for your applications to use, similar to how Amazon EC2 instance profiles provide credentials to Amazon EC2 instances.

Instead of creating and distributing long-term AWS credentials to containers or using the Amazon EC2 instance’s role, you can associate an IAM role that uses temporary credentials with an ECS task definition or `RunTask` [API](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-ecs-2014-11-13.html#runtask) operation. 

For more information on using IAM roles that container tasks can assume, see the [Task IAM role ](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html)topic in the *Amazon ECS Developer Guide*. For examples of using the task IAM role in the form of a `taskRoleArn` in task definitions, see [Example task definitions](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/firelens-example-taskdefs.html) also in the *Amazon ECS Developer Guide*.

## Assuming an IAM role in another AWS account
<a name="assuming-an-iam-role-in-another-aws-account"></a>

When you work in an AWS account (Account A) and want to assume a role in another account (Account B), you must first create an IAM role in Account B. This role allows entities in your account (Account A) to perform specific actions in Account B. For more information about cross-account access, see [Tutorial: Delegate Access Across AWS Accounts Using IAM Roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/tutorial_cross-account-with-roles.html).

After you create a role in Account B, record the Role ARN. You will use this ARN when you assume the role from Account A. You assume the role using the AWS credentials associated with your entity in Account A.

Create an AWS STS client with credentials for your AWS account. In the following, we used a credentials profile, but you can use any method. With the newly created AWS STS client, call assume-role and provide a custom sessionName. Retrieve the new temporary credentials from the result. Credentials last an hour by default.

 **Sample Code** 

```
$stsClient = new Aws\Sts\StsClient([
    'profile' => 'default',
    'region' => 'us-east-2',
    'version' => '2011-06-15'
]);

$ARN = "arn:aws:iam::123456789012:role/xaccounts3access";
$sessionName = "s3-access-example";

$result = $stsClient->AssumeRole([
      'RoleArn' => $ARN,
      'RoleSessionName' => $sessionName,
]);

 $s3Client = new S3Client([
    'version'     => '2006-03-01',
    'region'      => 'us-west-2',
    'credentials' =>  [
        'key'    => $result['Credentials']['AccessKeyId'],
        'secret' => $result['Credentials']['SecretAccessKey'],
        'token'  => $result['Credentials']['SessionToken']
    ]
]);
```

For more information, see [Using IAM Roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html) or [AssumeRole](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sts-2011-06-15.html#assumerole) in the AWS SDK for PHP API Reference.

## Using an IAM role with web identity
<a name="using-an-iam-role-with-web-identity"></a>

Web Identity Federation enables customers to use third-party identity providers for authentication when accessing AWS resources. Before you can assume a role with web identity, you must create an IAM role and configure a web identity provider (IdP). For more information, see [Creating a Role for Web Identity or OpenID Connect Federation (Console)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-idp_oidc.html).

After [creating an identity provider](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html) and [creating a role for your web identity](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-idp_oidc.html), use an AWS STS client to authenticate a user. Provide the webIdentityToken and ProviderId for your identity, and the Role ARN for the IAM role with permissions for the user.

 **Sample Code** 

```
$stsClient = new Aws\Sts\StsClient([
    'profile' => 'default',
    'region' => 'us-east-2',
    'version' => '2011-06-15'
]);

$ARN = "arn:aws:iam::123456789012:role/xaccounts3access";
$sessionName = "s3-access-example";
$duration = 3600;

$result = $stsClient->AssumeRoleWithWebIdentity([
      'WebIdentityToken' => "FACEBOOK_ACCESS_TOKEN",
      'ProviderId' => "graph.facebook.com",
      'RoleArn' => $ARN,
      'RoleSessionName' => $sessionName,
]);

 $s3Client = new S3Client([
    'version'     => '2006-03-01',
    'region'      => 'us-west-2',
    'credentials' =>  [
        'key'    => $result['Credentials']['AccessKeyId'],
        'secret' => $result['Credentials']['SecretAccessKey'],
        'token'  => $result['Credentials']['SessionToken']
    ]
]);
```

For more information, see [AssumeRoleWithWebIdentity—Federation Through a Web-based Identity Provider](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_assumerolewithwebidentity.html) or [AssumeRoleWithWebIdentity](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sts-2011-06-15.html#assumerolewithwebidentity) in the AWS SDK for PHP API Reference.

## Assume role with profile
<a name="assume-role-with-profile"></a>

### Define profiles in `~/.aws/credentials`
<a name="assume-role-profile-credentials-file"></a>

You can configure the AWS SDK for PHP to use an IAM role by defining a profile in `~/.aws/credentials`.

Create a new profile with the `role_arn` setting for the role you want assumed. Also include the `source_profile` setting for another profile with credentials that have permissions to assume the IAM role. For more details on these configuration settings, see [Assume role credentials](https://docs.aws.amazon.com/sdkref/latest/guide/feature-assume-role-credentials.html) in the *AWS SDKs and Tools Reference Guide*.

For example, in the following `~/.aws/credentials`, the `project1` profile sets the `role_arn` and specifies the `default` profile as the source for credentials to verify that the entity associated with them can assume the role.

```
[project1]
role_arn = arn:aws:iam::123456789012:role/testing
source_profile = default
role_session_name = OPTIONAL_SESSION_NAME

[default]
aws_access_key_id = YOUR_AWS_ACCESS_KEY_ID
aws_secret_access_key = YOUR_AWS_SECRET_ACCESS_KEY
aws_session_token= YOUR_AWS_SESSION_TOKEN
```

If you set the `AWS_PROFILE` environment variable, or you use `profile` parameter when you instantiate a service client, the role specified in `project1` is assumed, using the `default` profile as the source credentials.

The following snippet shows the use of the `profile` parameter in an `S3Client` constructor. The `S3Client` will have the permissions associated with the role associated with the `project1` profile.

```
$s3 = new Aws\S3\S3Client([
    'region' => 'us-east-1',
    'version' => '2006-03-01',
    'profile' => 'project1'
]);
```

### Define profiles in `~/.aws/config`
<a name="assume-role-profile-config-file"></a>

The `~/.aws/config` file can also contain profiles that you want to be assumed. If you set the environment variable `AWS_SDK_LOAD_NONDEFAULT_CONFIG`, the SDK for PHP loads profiles from the `config` file. When `AWS_SDK_LOAD_NONDEFAULT_CONFIG` is set, the SDK loads profiles from both `~/.aws/config` and `~/.aws/credentials`. Profiles from `~/.aws/credentials` are loaded last and take precedence over a profile from `~/.aws/config` with the same name. Profiles from either location can serve as the `source_profile` or the profile to be assumed.

The following example uses the `project1` profile defined in the `config` file and the `default` profile in the `credentials` file. The `AWS_SDK_LOAD_NONDEFAULT_CONFIG` is also set.

```
# Profile in ~/.aws/config.

[profile project1]
role_arn = arn:aws:iam::123456789012:role/testing
source_profile = default
role_session_name = OPTIONAL_SESSION_NAME
```

```
# Profile in ~/.aws/credentials.

[default]
aws_access_key_id = YOUR_AWS_ACCESS_KEY_ID
aws_secret_access_key = YOUR_AWS_SECRET_ACCESS_KEY
aws_session_token= YOUR_AWS_SESSION_TOKEN
```

When the `S3Client` constructor runs that is shown the following snippet, the role defined in the `project1` profile will be assumed using credentials associated with the `default` profile.

```
$s3 = new Aws\S3\S3Client([
    'region' => 'us-east-1',
    'version' => '2006-03-01',
    'profile' => 'project1'
]);
```

# Use temporary credentials from AWS STS in the SDK for PHP
<a name="guide_credentials_temporary"></a>

 AWS Security Token Service (AWS STS) enables you to request limited privilege, **temporary credentials** for IAM users, or for users that you authenticate via identity federation. For deeper understanding, see [Temporary Security Credentials](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html) in the *IAM User Guide*. You can use temporary security credentials to access most AWS services. For a list of the services that accept temporary security credentials, see [AWS services that work with IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-services-that-work-with-iam.html) in the *IAM User Guide*.

One common use case for temporary credentials is to grant mobile or client-side applications access to AWS resources by authenticating users through third-party identity providers (see [Web Identity Federation](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_oidc.html)).

## Getting temporary credentials
<a name="getting-temporary-credentials"></a>

AWS STS has several operations that return temporary credentials, but the `GetSessionToken` operation is the simplest to demonstrate. The following snippet retrieves temporary credentials by calling the `getSessionToken` method of the PHP SDK's STS client.

```
$sdk = new Aws\Sdk([
    'region'   => 'us-east-1',
]);

$stsClient = $sdk->createSts();

$result = $stsClient->getSessionToken();
```

The result for `GetSessionToken` and the other AWS STS operations always contains a `'Credentials'` value. If you print the `$result` (for example by using `print_r($result)`), it looks like the following.

```
Array
(
    ...
    [Credentials] => Array
    (
        [SessionToken] => '<base64 encoded session token value>'
        [SecretAccessKey] => '<temporary secret access key value>'
        [Expiration] => 2013-11-01T01:57:52Z
        [AccessKeyId] => '<temporary access key value>'
    )
    ...
)
```

## Providing temporary credentials to the AWS SDK for PHP
<a name="providing-temporary-credentials-to-the-sdk-php"></a>

You can use temporary credentials with another AWS client by instantiating the client and passing in the values received from AWS STS directly.

```
use Aws\S3\S3Client;

$result = $stsClient->getSessionToken();

$s3Client = new S3Client([
    'version'     => '2006-03-01',
    'region'      => 'us-west-2',
    'credentials' => [
        'key'    => $result['Credentials']['AccessKeyId'],
        'secret' => $result['Credentials']['SecretAccessKey'],
        'token'  => $result['Credentials']['SessionToken']
    ]
]);
```

You can also construct an `Aws\Credentials\Credentials` object and use that when instantiating the client.

```
use Aws\Credentials\Credentials;
use Aws\S3\S3Client;

$result = $stsClient->getSessionToken();

$credentials = new Credentials(
    $result['Credentials']['AccessKeyId'],
    $result['Credentials']['SecretAccessKey'],
    $result['Credentials']['SessionToken']
);

$s3Client = new S3Client([
    'version'     => '2006-03-01',
    'region'      => 'us-west-2',
    'credentials' => $credentials
]);
```

However, the *best* way to provide temporary credentials is to use the `createCredentials()` helper method included with the `StsClient`. This method extracts the data from an AWS STS result and creates the `Credentials` object for you.

```
$result = $stsClient->getSessionToken();
$credentials = $stsClient->createCredentials($result);

$s3Client = new S3Client([
    'version'     => '2006-03-01',
    'region'      => 'us-west-2',
    'credentials' => $credentials
]);
```

For more information about why you might need to use temporary credentials in your application or project, see [Scenarios for Granting Temporary Access](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html) in the AWS STS documentation.

# Create anonymous clients in the SDK for PHP
<a name="guide_credentials_anonymous"></a>

In some cases, you might want to create a client that is not associated with any credentials. This enables you to make anonymous requests to a service.

For example, you can configure both Amazon S3 objects and Amazon CloudSearch domains to allow anonymous access.

To create an anonymous client, you set the `'credentials'` option to `false`.

```
$s3Client = new S3Client([
    'version'     => 'latest',
    'region'      => 'us-west-2',
    'credentials' => false
]);

// Makes an anonymous request. The object would need to be publicly
// readable for this to succeed.
$result = $s3Client->getObject([
    'Bucket' => 'amzn-s3-demo-bucket',
    'Key'    => 'my-key',
]);
```