

# Configuring service clients in the AWS SDK for Swift
<a name="configuring"></a>

 To programmatically access AWS services, SDKs use a client class/object for each AWS service. For example, if your application needs to access Amazon EC2, your application creates an Amazon EC2 client object to interface with that service. You then use the service client to make requests to that AWS service. 

To make a request to an AWS service, you must first create a service client. For each AWS service your code uses, it has its own crate/library/gem/package and its own dedicated type for interacting with it. The client exposes one method for each API operation exposed by the service. 

There are many alternative ways to configure SDK behavior, but ultimately everything has to do with the behavior of service clients. Any configuration has no effect until a service client that is created from them is used.

You must establish how your code authenticates with AWS when you develop with AWS services. You must also set the AWS Region you want to use.

The [AWS SDKs and Tools Reference Guide](https://docs.aws.amazon.com/sdkref/latest/guide/) also contains settings, features, and other foundational concepts common among many of the AWS SDKs. 

**Topics**
+ [Client configuration externally](config-external.md)
+ [Client configuration in code](config-code.md)
+ [AWS Region](region.md)
+ [Credential providers](credential-providers.md)
+ [Retry](using-retry.md)
+ [HTTP](http.md)

# Configuring AWS SDK for Swift service clients externally
<a name="config-external"></a>

Many configuration settings can be handled outside of your code. When configuration is handled externally, the configuration is applied across all of your applications. Most configuration settings can be set as either environment variables or in a separate shared AWS `config` file. The shared `config` file can maintain separate sets of settings, called profiles, to provide different configurations for different environments or tests.

Environment variables and shared `config` file settings are standardized and shared across AWS SDKs and tools to support consistent functionality across different programming languages and applications.

See the *AWS SDKs and Tools Reference Guide* to learn about configuring your application through these methods, plus details on each cross-sdk setting. To see all the all settings that the SDK can resolve from the environment variables or configuration files, see the [Settings reference](https://docs.aws.amazon.com/sdkref/latest/guide/settings-reference.html) in the *AWS SDKs and Tools Reference Guide*.

To make a request to an AWS service, you first instantiate a client for that service. You can configure common settings for service clients such as timeouts, the HTTP client, and retry configuration. 

Each service client requires an AWS Region and a credential provider. The SDK uses these values to send requests to the correct Region for your resources and to sign requests with the correct credentials. You can specify these values programmatically in code or have them automatically loaded from the environment.

The SDK has a series of places (or sources) that it checks in order to find a value for configuration settings.

1. Any explicit setting set in the code or on a service client itself takes precedence over anything else.

1. Environment variables
   + For details on setting environment variables, see [environment variables](https://docs.aws.amazon.com/sdkref/latest/guide/environment-variables.html) in the *AWS SDKs and Tools Reference Guide*.
   + Note that you can configure environment variables for a shell at different levels of scope: system-wide, user-wide, and for a specific terminal session.

1. Shared `config` and `credentials` files
   + For details on setting up these files, see the [Shared `config` and `credentials` files](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html) in the *AWS SDKs and Tools Reference Guide*.

1. Optionally, the configuration is looked for on Amazon Elastic Container Service.

1. Optionally, the configuration can be taken from Amazon EC2 instance metadata.

1. Any default value provided by the SDK source code itself is used last.
   + Some properties, such as Region, don't have a default. You must specify them either explicitly in code, in an environment setting, or in the shared `config` file. If the SDK can't resolve required configuration, API requests can fail at runtime.

**Note**  
The AWS SDK for Swift's default credential resolver chain does not include the SSO credential resolver. You must explicitly configure service instances to use it if desired.

# Configuring AWS SDK for Swift service clients in code
<a name="config-code"></a>

When configuration is handled directly in code, the configuration scope is limited to the application that uses that code. Within that application, there are options for the global configuration of all service clients, the configuration to all clients of a certain AWS service type, or the configuration to a specific service client instance.

## Configuration data types
<a name="configurations-vary-by-service"></a>

Each AWS service has its own configuration class that you use to specify adjust options for that client type. All of these classes are based on a number of protocols that together describe all the configuration options available for that client. This includes options such as the Region and credentials, which are always needed in order to access an AWS service.

For Amazon S3, the configuration class is called `[S3Client.S3ClientConfiguration](https://sdk.amazonaws.com/swift/api/awss3/latest/documentation/awss3/s3client/s3clientconfiguration)` which is defined like this:

```
extension S3Client {
    public class S3ClientConfiguration: AWSClientRuntime.AWSDefaultClientConfiguration &
            AWSClientRuntime.AWSRegionClientConfiguration &
            ClientRuntime.DefaultClientConfiguration &
            ClientRuntime.DefaultHttpClientConfiguration {
        
        // Service-specific properties are defined here, including:

        public var region: Swift.String?

        // ... and so on.
   }
}
```

As a result, `S3ClientConfiguration` includes its own properties and also all the properties defined in those protocols, making it a complete description of an Amazon S3 client's configuration. Corresponding configuration classes are defined by every AWS service.

By creating a custom configuration object and using it when creating a service client object, you can customize the client by specifying a configuration source from which credentials and other options are taken. Otherwise, you can directly specify the credentials instead of letting the SDK obtain them automatically.

## Configuring a client
<a name="using-custom-configurations"></a>

When only changing common options, you can often specify the custom values for your configuration when instantiating the service’s client object. If the client class constructor doesn't support the option you need to change, then create and specify a configuration object with the type that corresponds to the client class.

### Creating a client with only a custom Region
<a name="instantiating-a-client-with-only-a-custom-region"></a>

Most services let you directly specify the Region when you call their constructors. For example, to create an Amazon S3 client configured for the Region `af-south-1`, specify the `region` parameter when creating the client, as shown.

```
do {
    let s3 = try S3Client(region: "af-south-1")

    // Use the client.
} catch {
    // Handle the error.
    dump(error, name: "Error accessing S3 service")
}
```

This lets you handle a common client configuration scenario (specifying a Region while using the default values for all other options) without going through the full configuration process. That process is covered in the next topic.

### Creating and using a custom configuration
<a name="creating-and-using-a-custom-configuration"></a>

To customize the configuration of an AWS service, create a configuration object of the appropriate type for the service. Then pass that configuration object into the service client's constructor as the value of its `config` parameter.

For example, to configure an Amazon S3 client, create an object of type `[S3Client.S3ClientConfiguration](https://sdk.amazonaws.com/swift/api/awss3/latest/documentation/awss3/s3client/s3clientconfiguration)`. Set the properties that you want to change, then pass the configuration object into `[S3Client(config:)](https://sdk.amazonaws.com/swift/api/awss3/latest/documentation/awss3/s3client/init(config:))`.

The following example creates a new Amazon S3 client configured with the following options:
+ The AWS Region is set to `us-east-1`.
+ An exponential backoff strategy with default options is selected instead of the default backoff strategy.
+ The retry mode is set to `RetryStrategyOptions.RateLimitingMode.adaptive`. See [Retry behavior](https://docs.aws.amazon.com/sdkref/latest/guide/feature-retry-behavior.html) in the *AWS SDKs and Tools Reference Guide* for details.
+ The maximum number of retries is set to 5.

```
        // Create an Amazon S3 client configuration object that specifies the
        // region as "us-east-1", an exponential backoff strategy, the
        // adaptive retry mode, and the maximum number of retries as 5.

        await SDKLoggingSystem().initialize(logLevel: .debug)

        let config: S3Client.S3ClientConfiguration

        do {
            config = try await S3Client.S3ClientConfiguration(
                awsRetryMode: .standard,
                maxAttempts: 3,
                region: "us-east-1"
            )
        } catch {
            print("Error: Unable to create configuration")
            dump(error)
            exit(1)
        }

        // Create an Amazon S3 client using the configuration created above.

        let client = S3Client(config: config)
```

If an error occurs creating the configuration, an error message is displayed and the details are dumped to the console. The program then exits. In a real world application, a more constructive approach should be taken when handling this error, such as falling back to a different configuration or using the default configuration, if doing so is appropriate for your application.

# Setting the AWS Region for the AWS SDK for Swift
<a name="region"></a>

You can access AWS services that operate in a specific geographic area by using AWS Regions. This can be useful both for redundancy and to keep your data and applications running close to where you and your users access them.

**Important**  
Most resources reside in a specific AWS Region and you must supply the correct Region for the resource when using the SDK.

You must set a default AWS Region for the SDK for Swift to use for AWS requests. This default is used for any SDK service method calls that aren't specified with a Region. 

For examples on how to set the default region through the shared AWS `config` file or environment variables, see [AWS Region](https://docs.aws.amazon.com/sdkref/latest/guide/feature-region.html) in the *AWS SDKs and Tools Reference Guide*.

## Specifying the Region programmatically
<a name="instantiating-a-client-with-only-a-custom-region"></a>

Most services let you directly specify the Region when you call their constructors. For example, to create an Amazon S3 client configured for the Region `af-south-1`, specify the `region` parameter when creating the client, as shown.

```
do {
    let s3 = try S3Client(region: "af-south-1")

    // Use the client.
} catch {
    // Handle the error.
    dump(error, name: "Error accessing S3 service")
}
```

This lets you handle a common client configuration scenario (specifying a Region while using the default values for all other options) without going through the full configuration process. That process is covered in [Creating and using a custom configuration](config-code.md#creating-and-using-a-custom-configuration).

# Using AWS SDK for Swift credential providers
<a name="credential-providers"></a>

 All requests to AWS must be cryptographically signed by using credentials issued by AWS. At runtime, the SDK retrieves configuration values for credentials by checking several locations.

If the retrieved configuration includes [AWS IAM Identity Center single sign-on access settings](authenticating.md), the SDK works with the IAM Identity Center to retrieve temporary credentials that it uses to make request to AWS services.

If the retrieved configuration includes [temporary credentials](https://docs.aws.amazon.com/sdkref/latest/guide/access-temp-idc.html), the SDK uses them to make AWS service calls. Temporary credentials consist of access keys and a session token.

Authentication with AWS can be handled outside of your codebase. Many authentication methods can be automatically detected, used, and refreshed by the SDK using the credential provider chain.

For guided options for getting started on AWS authentication for your project, see [Authentication and access](https://docs.aws.amazon.com/sdkref/latest/guide/access.html) in the *AWS SDKs and Tools Reference Guide*.

## The credential provider chain
<a name="credproviders-default-credentials-provider-chain"></a>

If you don't explicitly specify a credential provider when constructing a client, the AWS SDK for Swift uses a credential provider chain that checks a series of places where you can supply credentials. Once the SDK finds credentials in one of these locations, the search stops. 

## Credential retrieval order
<a name="credproviders-credential-retrieval-order"></a>

The credential provider chain searches for credentials using the following predefined sequence:

1. **Access key environment variables**

   The SDK attempts to load credentials from the `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY`, and `AWS_SESSION_TOKEN` environment variables.

1. **The shared AWS `config` and `credentials` files**

   The SDK attempts to load credentials from the `[default]` profile in the shared AWS `config` and `credentials` files. You can use the `AWS_PROFILE` environment variable to choose a named profile you want the SDK to load instead of using `[default]`. The `config` and `credentials` files are shared by various AWS SDKs and tools. For more information on these files, see the [Shared `config` and `credentials` files](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html) in the *AWS SDKs and Tools Reference Guide*.

   If you use console credentials to authenticate, this is when the SDK uses the login token that was set up by running AWS CLI command `aws login`. The SDK uses the temporary credentials from the cached token when it calls AWS services. For detailed information about this process, see [Understand SDK credential resolution for AWS services](https://docs.aws.amazon.com/sdkref/latest/guide/understanding-sso.html#idccredres) in the *AWS SDKs and Tools Reference Guide*.

   If you use IAM Identity Center to authenticate, this is when the SDK uses the single sign-on token that was set up by running AWS CLI command `aws sso login`. The SDK uses the temporary credentials that the IAM Identity Center exchanged for a valid token. The SDK then uses the temporary credentials when it calls AWS services. For detailed information about this process, see [Understand SDK credential resolution for AWS services](https://docs.aws.amazon.com/sdkref/latest/guide/understanding-sso.html#idccredres) in the *AWS SDKs and Tools Reference Guide*.
   +  For guidance on configuring this provider, see [IAM Identity Center authentication](https://docs.aws.amazon.com/sdkref/latest/guide/access-sso.html) in the *AWS SDKs and Tools Reference Guide*.
   +  For details on SDK configuration properties for this provider, see [IAM Identity Center credential provider](https://docs.aws.amazon.com/sdkref/latest/guide/feature-sso-credentials.html) in the *AWS SDKs and Tools Reference Guide*.

1. **AWS STS web identity**

   When creating mobile applications or client-based web applications that require access to AWS, AWS Security Token Service (AWS STS) returns a set of temporary security credentials for federated users who are authenticated through a public identity provider (IdP).
   + When you specify this in a profile, the SDK or tool attempts to retrieve temporary credentials using AWS STS `AssumeRoleWithWebIdentity` API method. For details on this method, see [AssumeRoleWithWebIdentity](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html) in the *AWS Security Token Service API Reference*.
   +  For guidance on configuring this provider, see [Federate with web identity or OpenID Connect](https://docs.aws.amazon.com/sdkref/latest/guide/access-assume-role.html#webidentity) in the *AWS SDKs and Tools Reference Guide*.
   +  For details on SDK configuration properties for this provider, see [Assume role credential provider](https://docs.aws.amazon.com/sdkref/latest/guide/feature-assume-role-credentials.html) in the *AWS SDKs and Tools Reference Guide*.

1. **Amazon ECS and Amazon EKS container credentials **

   Your Amazon Elastic Container Service tasks and Kubernetes service accounts can have an IAM role associated with them. The permissions granted in the IAM role are assumed by the containers running in the task or containers of the pod. This role allows your application code (on the container) to use other AWS services.

   The SDK attempts to retrieve credentials from the `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI` or `AWS_CONTAINER_CREDENTIALS_FULL_URI` environment variables, which can be set automatically by Amazon ECS and Amazon EKS.
   + For details on setting up this role for Amazon ECS, see [ Amazon ECS task IAM role](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html) in the *Amazon Elastic Container Service Developer Guide*.
   + For Amazon EKS setup information, see [Setting up the Amazon EKS Pod Identity Agent](https://docs.aws.amazon.com/eks/latest/userguide/pod-id-agent-setup.html) in the **Amazon EKS User Guide**.
   +  For details on SDK configuration properties for this provider, see [Container credential provider](https://docs.aws.amazon.com/sdkref/latest/guide/feature-container-credentials.html) in the *AWS SDKs and Tools Reference Guide*.

1. **Amazon EC2 Instance Metadata Service **

   Create an IAM role and attach it to your instance. The SDK application on the instance attempts to retrieve the credentials provided by the role from the instance metadata. 
   + For details on setting up this role and using metadata, [IAM roles for Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html) and [Work with instance metadata](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) in the *Amazon EC2 User Guide*.
   +  For details on SDK configuration properties for this provider, see [IMDS credential provider](https://docs.aws.amazon.com/sdkref/latest/guide/feature-imds-credentials.html) in the *AWS SDKs and Tools Reference Guide*.

For details on AWS credential provider configuration settings, see [Standardized credential providers](https://docs.aws.amazon.com/sdkref/latest/guide/standardized-credentials.html) in the *Settings reference* of the *AWS SDKs and Tools Reference Guide*.

## Credential identity resolvers
<a name="identity-types"></a>

A **credential identity resolver** is an object that takes some form of identity, verifies that it's valid for use by the application, and returns credentials that can be used when using an AWS service . There are several supported ways to obtain a valid identity, and each has a corresponding credential identity resolver type available for you to use, depending on which authorization methods you want to use.

The credential identity resolver acts as an adaptor between the identity and the AWS service. By providing a credential identity resolver to the service instead of directly providing the user's credentials, the service is able to fetch currently-valid credentials for the identity at any time, as long as the identity provider allows it.

Identity features in the AWS SDK for Swift are defined in the module `AWSSDKIdentity`. In the `AWSSDKIdentity` module, credentials are represented by the struct `[AWSCredentialIdentity](https://sdk.amazonaws.com/swift/api/smithyidentity/latest/documentation/smithyidentity/awscredentialidentity)`. See [AWS security credentials](/IAM/latest/UserGuide/security-creds.html#AccessKeys) in the IAM User Guide for further information about AWS credentials.

There are several credential identity resolver types available as a means of obtaining an identity to use for authentication. Some credential identity resolvers are specific to a given source while others encompass an assortment of identity sources that share similar technologies. For example, the `STSWebIdentityCredentialIdentityResolver`, which uses a JSON Web Token (JWT) as the source identity for which to return AWS credentials. The JWT can come from a number of different services, including Amazon Cognito federated identities, Sign In With Apple, Google, or Facebook. See [Identity pools third-party identity providers](/cognito/latest/developerguide/external-identity-providers.html) for information on third-party identity providers.

`[CachedAWSCredentialIdentityResolver](https://sdk.amazonaws.com/swift/api/awssdkidentity/latest/documentation/awssdkidentity/cachedawscredentialidentityresolver)`  
A credential identity resolver that is chained with another one so it can cache the resolved identity for re-use until an expiration time elapses.

`[CognitoAWSCredentialIdentityResolver](https://sdk.amazonaws.com/swift/api/awssdkidentity/latest/documentation/awssdkidentity/cognitoawscredentialidentityresolver)`  
A credential identity resolver that uses an Amazon Cognito Identity Pool or a Cognito Identity ID to resolve credentials.

`[CustomAWSCredentialIdentityResolver](https://sdk.amazonaws.com/swift/api/awssdkidentity/latest/documentation/awssdkidentity/customawscredentialidentityresolver)`  
A credential identity resolver that uses another credential identity resolver's output to resolve the credentials in a custom way.

`[DefaultAWSCredentialIdentityResolverChain](https://sdk.amazonaws.com/swift/api/awssdkidentity/latest/documentation/awssdkidentity/defaultawscredentialidentityresolverchain)`  
Represents a chain of credential identity resolvers that attempt to resolve the identity following the standard search order. See [Credential provider chain](https://docs.aws.amazon.com/sdkref/latest/guide/standardized-credentials.html#credentialProviderChain) in the AWS SDKs and Tools Reference Guide for details on the credential provider chain.

`[ECSAWSCredentialIdentityResolver](https://sdk.amazonaws.com/swift/api/awssdkidentity/latest/documentation/awssdkidentity/ecsawscredentialidentityresolver)`  
Obtains credentials from an Amazon Elastic Container Service container's metadata.

`[EnvironmentAWSCredentialIdentityResolver](https://sdk.amazonaws.com/swift/api/awssdkidentity/latest/documentation/awssdkidentity/environmentawscredentialidentityresolver)`  
Resolves credentials using the environment variables `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_SESSION_TOKEN`.

`[IMDSAWSCredentialIdentityResolver](https://sdk.amazonaws.com/swift/api/awssdkidentity/latest/documentation/awssdkidentity/imdsawscredentialidentityresolver)`  
Uses IMDSv2 to fetch credentials within an Amazon Elastic Compute Cloud instance.

`[LoginAWSCredentialIdentityResolver](https://sdk.amazonaws.com/swift/api/awssdkidentity/latest/documentation/awssdkidentity/loginawscredentialidentityresolver)`  
 Resolves credentials using console credentials with AWS Signin.

`[ProcessAWSCredentialIdentityResolver](https://sdk.amazonaws.com/swift/api/awssdkidentity/latest/documentation/awssdkidentity/processawscredentialidentityresolver)`  
Resolves credentials by running a command or process. The process to run is sourced from a profile in the AWS `config` file. The profile key that identifies the process to use is `credential_process`.

`[ProfileAWSCredentialIdentityResolver](https://sdk.amazonaws.com/swift/api/awssdkidentity/latest/documentation/awssdkidentity/profileawscredentialidentityresolver)`  
Uses the specified profile from an AWS `config` file to resolve credentials.

`[SSOAWSCredentialIdentityResolver](https://sdk.amazonaws.com/swift/api/awssdkidentity/latest/documentation/awssdkidentity/ssoawscredentialidentityresolver)`  
Resolves credentials using a single-sign-on login with AWS IAM Identity Center.

[https://sdk.amazonaws.com/swift/api/awssdkidentity/latest/documentation/awssdkidentity/staticawscredentialidentityresolver](https://sdk.amazonaws.com/swift/api/awssdkidentity/latest/documentation/awssdkidentity/staticawscredentialidentityresolver)  
A credential resolver that uses specified credentials in the form of an `[AWSCredentialIdentity](https://sdk.amazonaws.com/swift/api/smithyidentity/latest/documentation/smithyidentity/awscredentialidentity)` object.

`[STSAssumeRoleAWSCredentialIdentityResolver](https://sdk.amazonaws.com/swift/api/awssdkidentity/latest/documentation/awssdkidentity/stsassumeroleawscredentialidentityresolver)`  
Uses another credential identity resolver to assume a specified AWS Identity and Access Management role, then fetch the assumed credentials using AWS Security Token Service.

[https://sdk.amazonaws.com/swift/api/awssdkidentity/latest/documentation/awssdkidentity/stswebidentityawscredentialidentityresolver](https://sdk.amazonaws.com/swift/api/awssdkidentity/latest/documentation/awssdkidentity/stswebidentityawscredentialidentityresolver)  
Exchanges a JSON Web Token (JWT) for credentials using AWS Security Token Service.

## Getting credentials from an identity
<a name="identity-steps"></a>

The process of using a credential identity resolver involves four primary steps:

1. Use an appropriate sign-in service to obtain an identity in a form supported by AWS.

1. Create a credential identity resolver of the type that corresponds to the given identity.

1. When creating an AWS service client object, provide the credential identity resolver as the value of its configuration's `awsCredentialIdentityResolver` property.

1. Call service functions using the service client object.

The following sections provide examples using some of the credential identity providers supported by AWS.

## Login credential identity resolver with AWS Signin
<a name="identity-login"></a>

Authenticating for an AWS service using console credentials requires first creating login token with AWS Command Line Interface. See [Login for AWS local development using console credentials](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sign-in.html) for more details.

Once the login token is created and cached by AWS CLI command **aws login** or **aws login --profile *profile-name***, your application can use `LoginAWSCredentialIdentityResolver` to obtain credentials using the established login token.

To create a Login credential identity resolver, create a new `LoginAWSCredentialIdentityResolver` that uses the desired settings for the profile name, `config` file path, and `credentials` file path. Any of these can be `nil` to use the same default value the AWS CLI would use.

**Note**  
To use credential identity resolvers, you must import the `AWSSDKIdentity` module:  

```
import AWSSDKIdentity
```

```
let identityResolver = try LoginAWSCredentialIdentityResolver(
    profileName: profile,
    configFilePath: config,
    credentialsFilePath: credentials
)
```

To use this resolver to provide credentials to an AWS service, set the service configuration's `awsCredentialIdentityResolver` to the created credential identity resolver.

```
// Get an S3Client with which to access Amazon S3.
let configuration = try await S3Client.S3ClientConfiguration(
    awsCredentialIdentityResolver: identityResolver
)
let client = S3Client(config: configuration)

// Use "Paginated" to get all the buckets. This lets the SDK handle
// the 'continuationToken' in "ListBucketsOutput".
let pages = client.listBucketsPaginated(
    input: ListBucketsInput(maxBuckets: 10)
)
```

## SSO credential identity resolvers with AWS IAM Identity Center
<a name="identity-sso"></a>

Authenticating for an AWS service using SSO requires first configuring SSO access using AWS IAM Identity Center. See [IAM Identity Center authentication for your SDK or tool](https://docs.aws.amazon.com/sdkref/latest/guide/access-sso.html) in the AWS SDKs and Tools Reference Guide for instructions on setting up IAM Identity Center and configuring SSO access on computers that will use your application.

Once a user has authenticated with the AWS Command Line Interface (AWS CLI) command **aws sso login** or **aws sso login --profile *profile-name***, your application can use an `[SSOAWSCredentialIdentityResolver](https://sdk.amazonaws.com/swift/api/awssdkidentity/latest/documentation/awssdkidentity/ssoawscredentialidentityresolver)` to obtain credentials using the established IAM Identity Center identity.

To create an SSO credential identity resolver, create a new `SSOAWSCredentialIdentityResolver` that uses the desired settings for the profile name, `config` file path, and `credentials` file path. Any of these can be `nil` to use the same default value the AWS CLI would use.

**Note**  
To use credential identity resolvers, you must import the `AWSSDKIdentity` module:  

```
import AWSSDKIdentity
```

```
            let identityResolver = try SSOAWSCredentialIdentityResolver(
                profileName: profile,
                configFilePath: config,
                credentialsFilePath: credentials
            )
```

To use the IAM Identity Center identity resolver to provide credentials to an AWS service, set the service configuration's `awsCredentialIdentityResolver` to the created credential identity resolver. 

```
        // Get an S3Client with which to access Amazon S3.
        let configuration = try await S3Client.S3ClientConfiguration(
            awsCredentialIdentityResolver: identityResolver
        )
        let client = S3Client(config: configuration)

        // Use "Paginated" to get all the buckets. This lets the SDK handle
        // the 'continuationToken' in "ListBucketsOutput".
        let pages = client.listBucketsPaginated(
            input: ListBucketsInput(maxBuckets: 10)
        )
```

With the service configured this way, each time the SDK accesses the AWS service, it uses the credentials returned by the SSO credential identity resolver to authenticate the request.

## Static credential identity resolvers
<a name="identity-example-static"></a>

**Warning**  
Static credential identity resolvers are highly unsafe unless used with care. They can return hard-coded credentials, which are inherently unsafe to use. Only use static credential identity resolvers when experimenting, testing, or generating safe static credentials from another source before using them.

Static credential identity resolvers use AWS credentials as an identity. To create a static credential identity resolver, create an `AWSCredentialIdentity` object with the static credentials, then create a new `StaticAWSCredentialIdentityResolver` that uses that identity.

**Note**  
To use credential identity resolvers, you must import the `AWSSDKIdentity` module:  

```
import AWSSDKIdentity
```

```
        let credentials = AWSCredentialIdentity(
            accessKey: accessKey,
            secret: secretKey,
            sessionToken: sessionToken
        )

        let identityResolver = try StaticAWSCredentialIdentityResolver(credentials)
```

To use the static credential identity resolver to provide credentials to an AWS service, use it as the service configuration's `awsCredentialIdentityResolver`.:

```
            let s3Configuration = try await S3Client.S3ClientConfiguration(
                awsCredentialIdentityResolver: identityResolver,
                region: region
            )
            let client = S3Client(config: s3Configuration)

            // Use "Paginated" to get all the buckets. This lets the SDK handle
            // the 'continuationToken' in "ListBucketsOutput".
            let pages = client.listBucketsPaginated(
                input: ListBucketsInput( maxBuckets: 10)
            )
```

When the service client asks the credential identity resolver for its credentials, the resolver returns the `AWSCredentialIdentity` struct's access key, secret, and session token.

The complete example is [available on GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/sts/AssumeRole).

## Amazon Cognito credential identity resolvers
<a name="identity-cognito-resolvers"></a>

To use Amazon Cognito to provide credentials to an AWS service, first create an object of type `CognitoAWSCredentialIdentityResolver`, specifying the Amazon Cognito Identity Pool ID of the identity pool to use for credentials:

```
        // Create a Cognito credential resolver that uses the Cognito Identity
        // Pool.
        let cognitoCredentialResolver = try CognitoAWSCredentialIdentityResolver(
            identityPoolId: identityPoolID,
            identityPoolRegion: region
        )
```

Once the credential identity resolver has been created, you can instruct service clients to use it to resolve credentials by including the `awsCredentialIdentityResolver` property in the client's configuration with its value set to the `CognitoAWSCredentialIdentityResolver`. 

```
        let s3Config = try await S3Client.S3ClientConfiguration(
            awsCredentialIdentityResolver: cognitoCredentialResolver,
            region: region
        )
        let s3Client = S3Client(config: s3Config)

        let listBucketsOutput = try await s3Client.listBuckets(
            input: ListBucketsInput()
        )
```

This example creates an Amazon S3 client that uses the Amazon Cognito credential identity resolver to authenticate when using the S3 client. All AWS actions performed using the client will authenticate using the resolved credentials, as shown here by calling `S3Client.listBuckets(input:)`.

## Additional information
<a name="identity-additional-information"></a>
+ [AWS SDKs and Tools Reference Guide](https://docs.aws.amazon.com/sdkref/latest/guide/standardized-credentials.html): SSO token provider configuration

# Configuring retry using the AWS SDK for Swift
<a name="using-retry"></a>

Calls to AWS services occasionally encounter problems or unexpected situations. Certain types of errors, such as throttling or transient errors, might be successful if the call is retried.

This page describes how to configure automatic retries with the AWS SDK for Swift.

## Default retry configuration
<a name="retries-default"></a>

By default, every service client is automatically configured with a standard retry strategy. The default configuration tries each action up to three times (the initial attempt plus two retries). The intervening delay between each call is configured with exponential backoff and random jitter to avoid retry storms. This configuration works for the majority of use cases but may be unsuitable in some circumstances, such as high-throughput systems.

The SDK attempts retries only on retryable errors. Examples of retryable errors are socket timeouts, service-side throttling, concurrency or optimistic lock failures, and transient service errors. Missing or invalid parameters, authentication/security errors, and misconfiguration exceptions are not considered retryable.

## Configuring retry
<a name="retries-configure"></a>

You can customize the standard retry strategy by setting the maximum number of attempts and the rate limiting strategy to use. To change the retry configuration, create a structure of type `S3ClientConfiguration` with the properties you wish to customize. For details on how to configure a service client, see [Configuring AWS SDK for Swift service clients in code](config-code.md).

### Maximum number of attempts
<a name="retries-max-attempts"></a>

You can customize the maximum number of attempts by specifying a value for the `S3ClientConfiguration` structure's `maxAttempts` property. The default value is 3.

### Retry mode
<a name="retries-rate-limiting-mode"></a>

The retry mode can be set by changing the `S3ClientConfiguration` structure's `retryMode`. The available values are provided by the `enum` `AWSRetryMode`.

#### Legacy
<a name="retries-rate-limiting-mode-legacy"></a>

The `legacy` retry mode—the default—is the original standard retry mode. In this mode, requests may be sent immediately, and are not delayed for rate limiting when throttling is detected. Requests are only delayed according to the backoff strategy in use, which is exponentially by default.

#### Standard
<a name="retries-rate-limiting-mode-standard"></a>

In the AWS SDK for Swift, the `standard` mode is the same as legacy mode.

#### Adaptive
<a name="retries-rate-limiting-mode-adaptive"></a>

In the `adaptive` retry mode, initial and retry requests may be delayed by an additional amount when throttling is detected. This is intended to reduce congestion when throttling is in effect. This is sometimes called "client-side rate limiting" mode, and is available opt-in. You should only use adaptive mode when advised to do so by an AWS representative.

### Example
<a name="retries-example"></a>

First, import the modules needed to configure retry:

```
import AWSS3
import SmithyRetries
import SmithyRetriesAPI
```

Then create the custom configuration. This example's `S3ClientConfiguration` asks for the client to make up to three attempts for each action, using the `adaptive` retry mode.

```
        let config: S3Client.S3ClientConfiguration

        // Create an Amazon S3 client configuration object that specifies the
        // adaptive retry mode and sets the maximum number of attempts to 3.
        // If that fails, create a default configuration instead.

        do {
            config = try await S3Client.S3ClientConfiguration(
                awsRetryMode: .adaptive,
                maxAttempts: 3
            )
        } catch {
            do {
                config = try await S3Client.S3ClientConfiguration()
            } catch {
                print("Error: Unable to configure Amazon S3.")
                dump(error)
                return
            }
        }

        // Create an Amazon S3 client using the configuration created above.

        let client = S3Client(config: config)
```

It first attempts to create the configuration using the application's preferred settings. If that fails, a default configuration is created instead. If that also fails, the example outputs an error message. A real-world application might instead present an error message and let the user decide what to do.

# Configuring HTTP-level settings within the AWS SDK for Swift
<a name="http"></a>

## Configuring HTTP timeouts
<a name="configuring-http-timeouts"></a>

The AWS SDK for Swift supports two types of timeout on HTTP clients. These are configured by setting the corresponding properties on the service client's `httpClientConfiguration` structure to the number of seconds to allow before timing out:
+ **`connectTimeout`** specifies how much time to allow before an attempt to open an HTTP connection times out.
+ **`socketTimeout`** specifies how long to wait for a socket to respond to a request before timing out.

```
        do {
            let config = try await S3Client.S3ClientConfiguration(
                region: region,
                httpClientConfiguration: HttpClientConfiguration(
                    connectTimeout: 2,
                    socketTimeout: 5
                )
            )
            let s3Client = S3Client(config: config)
            _ = try await s3Client.listBuckets(input: ListBucketsInput())
            print("*** Success!")
        } catch CommonRunTimeError.crtError(let crtError) {
            print("*** An error occurred accessing the bucket list: \(crtError.message)")
        } catch {
            print("*** Unexpected error occurred requesting the bucket list.")
        }
```

This example creates an Amazon S3 client that times out HTTP connection attempts after 2 seconds, while allowing up to 5 seconds for sockets to time out.

## Customizing HTTP headers
<a name="configuring-http-headers"></a>

You can add default headers to your HTTP requests by setting the service client's `httpConfiguration.defaultHeaders` property to a `Headers` structure header which is initialized with a dictionary that maps header names to their values.

**Important**  
Setting default headers that interfere with headers the AWS service expects may result in unpredictable results.

This example creates an Amazon S3 client whose HTTP configuration adds two custom headers to HTTP requests sent by the client:

```
import ClientRuntime
import AWSS3
import SmithyHTTPAPI
import AwsCommonRuntimeKit

        let config = try await S3Client.S3ClientConfiguration(
            region: region,
            httpClientConfiguration: HttpClientConfiguration(
                defaultHeaders: Headers(
                    [
                        "X-My-Custom-Header": "CustomHeaderValue",
                        "X-Another-Custom-Header": "AnotherCustomValue"
                    ]
                )
            )
        )
        let s3Client = S3Client(config: config)
```

## HTTP/1 vs. HTTP/2
<a name="configuring-http-version"></a>

HTTP version 1.1 is adequate for most tasks when using AWS services, and is used automatically for these. However, there are times when HTTP version 2 is required. While some AWS SDKs require you to specifically customize the service client to use HTTP/2, the SDK for Swift detects when a function uses event streaming and automatically uses HTTP/2 for these actions. Your code doesn't need to do anything to handle this.

## Using a custom HTTP client
<a name="configuring-http-client"></a>

To use a custom HTTP client, create a client class which conforms to the `[HTTPClient](https://sdk.amazonaws.com/swift/api/smithyhttpapi/latest/documentation/smithyhttpapi/httpclient)` class in the `SmithyHTTPAPI` module. This protocol requires a single function: [https://sdk.amazonaws.com/swift/api/smithyhttpapi/latest/documentation/smithyhttpapi/httpclient/send(request:)](https://sdk.amazonaws.com/swift/api/smithyhttpapi/latest/documentation/smithyhttpapi/httpclient/send(request:)), which returns a `[HTTPResponse](https://sdk.amazonaws.com/swift/api/smithyhttpapi/latest/documentation/smithyhttpapi/httpresponse)` object. You can then specify your custom HTTP client by setting the client configuration's `[httpClientEngine](https://sdk.amazonaws.com/swift/api/clientruntime/latest/documentation/clientruntime/defaultsdkruntimeconfiguration/httpclientengine)` property to an instance of your custom HTTP client class. 