Configure access credentials for OSS SDK for Swift

Updated at:

Configure access credentials before you use OSS SDK for Swift to make requests to Object Storage Service (OSS). Alibaba Cloud services use these credentials to verify your identity and access permissions. Select a credential type based on the authentication and authorization requirements of your scenario.

Prerequisites

  • OSS SDK for Swift — Add OSS SDK for Swift to your project. Every sample in this topic imports the AlibabaCloudOSS module.

  • RAM user and AccessKey — Create a Resource Access Management (RAM) user and an AccessKey pair for it. For instructions, see Create an AccessKey. The AccessKey ID and AccessKey secret are displayed only when you create the AccessKey pair, so save both values immediately. If you lose them, create a new AccessKey pair and rotate the credentials.

  • Region and endpoint — Each sample in this topic specifies the region ID of the bucket, such as cn-hangzhou for China (Hangzhou). The endpoint is optional: specify it only to send requests to a specific domain name, such as https://oss-cn-hangzhou.aliyuncs.com for China (Hangzhou). For the mapping between the regions and endpoints that OSS supports, see Regions and endpoints.

Select a credential provider

OSS SDK for Swift supports multiple methods to initialize a credential provider. The following table compares the methods so that you can select the one that meets the authentication and authorization requirements of your scenario.

Credential provider initialization methodScenariosRequires an existing AccessKey or Security Token Service (STS) tokenUnderlying credential typeCredential validity periodCredential rotation or refresh method
Use the AccessKey of a RAM userApplications that run in a secure and stable environment that is not prone to external attacks and that require long-term access to Alibaba Cloud services without frequent credential rotation.YesAccessKeyLong-termManual rotation
Use an STS temporary access credentialApplications that run in an untrusted environment and that require control over the validity period and permissions of access.YesSTS tokenTemporaryManual refresh
Custom credential providerApplications that require a credential source that the preceding methods do not cover.Depends on your implementationCustomCustomCustom

The AccessKey method and the STS method each support two variants:

  • Environment variables (Recommended) — The SDK reads the credentials from environment variables at runtime, so no credential value is stored in your source code.

  • Static credentials — Your code passes the credentials to StaticCredentialsProvider directly. Because the credentials are hard-coded, use this variant for testing only.

Use the AccessKey of a RAM user

Initialize the credential provider with the AccessKey (AccessKey ID and AccessKey secret) of your Alibaba Cloud account or a RAM user. Use this method if your application runs in a secure and stable environment that is not prone to external attacks, requires long-term access to OSS, and cannot rotate credentials frequently. This method requires you to maintain the AccessKey manually, which increases security risks and maintenance complexity.

Warning

An Alibaba Cloud account has full permissions on all of its resources. If the AccessKey of an Alibaba Cloud account is leaked, your system is at significant risk. Use the AccessKey of a RAM user that is granted only the minimum required permissions. For the AccessKey creation entry point, see Prerequisites.

Environment variables

  1. Configure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables with the AccessKey ID and AccessKey secret of the RAM user.

    Linux

    1. Run the following commands on the CLI to add the configurations of the environment variables to the ~/.bashrc file:

      echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
      echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
      1. Apply the changes.

        source ~/.bashrc
      2. Check whether the environment variables have taken effect:

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

    macOS

    1. Run the following command in the terminal to view the default shell type:

      echo $SHELL
      1. Configure environment variables based on the default shell type.

        Zsh
        1. Run the following commands to add the configurations of the environment variables to the ~/.zshrc file:

          echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
          echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
        2. Apply the changes.

          source ~/.zshrc
        3. Check whether the environment variables have taken effect:

          echo $OSS_ACCESS_KEY_ID
          echo $OSS_ACCESS_KEY_SECRET
        Bash
        1. Run the following commands to add the configurations of the environment variables to the ~/.bash_profile file:

          echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile
          echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile
        2. Apply the changes.

          source ~/.bash_profile
        3. Check whether the environment variables have taken effect:

          echo $OSS_ACCESS_KEY_ID
          echo $OSS_ACCESS_KEY_SECRET

    Windows

    CMD
    1. Run the following commands in CMD:

      setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
      setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
      1. Check whether the environment variables take effect:

        echo %OSS_ACCESS_KEY_ID%
        echo %OSS_ACCESS_KEY_SECRET%
    PowerShell
    1. Run the following commands in PowerShell:

      [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
      1. Check whether the environment variable takes effect:

        [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
        [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
  2. Restart or refresh your compilation and runtime environment, including the IDE, command-line interface, other desktop applications, and background services, so that the latest system environment variables are loaded.

  3. Pass the credential information through environment variables.

    import AlibabaCloudOSS
    import Foundation
    
    @main
    struct Main {
        static func main() async {
            // The region in which the bucket is located. Example: cn-hangzhou.
            let region = "cn-hangzhou"
            // Optional. The domain name that is used to access OSS.
            let endpoint: String? = nil
    
            // Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
            let credentialsProvider = EnvironmentCredentialsProvider()
    
            // Configure the parameters of the OSS client.
            let config = Configuration.default()
                .withRegion(region)        // Specify the region in which the bucket is located.
                .withCredentialsProvider(credentialsProvider)  // Specify the access credentials.
                
            // Specify a custom endpoint.
            if let endpoint = endpoint {
                config.withEndpoint(endpoint)
            }
            
            // Create an OSS client instance.
            let client = Client(config)
            
            // Use the client to make requests on objects, such as uploading, downloading, or managing objects.
        }
    }

Static credentials

The following sample code shows how to hard-code access credentials and explicitly specify the AccessKey to use.

Warning

Do not embed access credentials in an application that runs in a production environment. This method is intended for testing purposes only.

import AlibabaCloudOSS
import Foundation

@main
struct Main {
    static func main() async {
        // The region in which the bucket is located. Example: cn-hangzhou.
        let region = "cn-hangzhou"
        // Optional. The domain name that is used to access OSS.
        let endpoint: String? = nil

        // Specify the AccessKey ID and AccessKey secret of the RAM user.
        let accessKeyId = "yourAccessKeyID"
        let accessKeySecret = "yourAccessKeySecret"

        // Use StaticCredentialsProvider to directly specify the accessKeyId and accessKeySecret.
        let credentialsProvider = StaticCredentialsProvider(accessKeyId: accessKeyId,
                                                            accessKeySecret: accessKeySecret)

        // Configure the parameters of the OSS client.
        let config = Configuration.default()
            .withRegion(region)        // Specify the region in which the bucket is located.
            .withCredentialsProvider(credentialsProvider)  // Specify the access credentials.

        // Specify a custom endpoint.
        if let endpoint = endpoint {
            config.withEndpoint(endpoint)
        }

        // Create an OSS client instance.
        let client = Client(config)

        // Use the client to make requests on objects, such as uploading, downloading, or managing objects.
    }
}

Use an STS temporary access credential

Initialize the credential provider with the temporary credentials (AccessKey ID, AccessKey secret, and security token) that you obtain from Security Token Service (STS). Use this method if your application requires temporary access to OSS. Because you obtain and maintain the STS token yourself, this method increases security risks and maintenance complexity. To access OSS more than once, refresh the STS token manually.

Important

Environment variables

Configure the environment variables with the temporary credentials that you obtained from STS.

Warning
  • Use the temporary credentials (AccessKey ID, AccessKey secret, and security token) obtained from STS, not the AccessKey (AccessKey ID and AccessKey secret) of a RAM user.

  • The AccessKey ID obtained from STS starts with STS., for example, STS.L4aBSCSJVMuKg5U1****.

macOS, Linux, or Unix

export OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID>
export OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET>
export OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN>

Windows

set OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID>
set OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET>
set OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN>

Pass the credential information through environment variables.

import AlibabaCloudOSS
import Foundation

@main
struct Main {
    static func main() async {
        // The region in which the bucket is located. Example: cn-hangzhou.
        let region = "cn-hangzhou"
        // Optional. The domain name that is used to access OSS.
        let endpoint: String? = nil

        // Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET, and OSS_SESSION_TOKEN environment variables are configured.
        let credentialsProvider = EnvironmentCredentialsProvider()

        // Configure the parameters of the OSS client.
        let config = Configuration.default()
            .withRegion(region)        // Specify the region in which the bucket is located.
            .withCredentialsProvider(credentialsProvider)  // Specify the access credentials.

        // Specify a custom endpoint.
        if let endpoint = endpoint {
            config.withEndpoint(endpoint)
        }

        // Create an OSS client instance.
        let client = Client(config)

        // Use the client to make requests on objects, such as uploading, downloading, or managing objects.
    }
}

Static credentials

The following sample code shows how to hard-code access credentials and explicitly specify the temporary AccessKey to use.

Warning

Do not embed access credentials in an application that runs in a production environment. This method is intended for testing purposes only.

import AlibabaCloudOSS
import Foundation

@main
struct Main {
    static func main() async {
        // The region in which the bucket is located. Example: cn-hangzhou.
        let region = "cn-hangzhou"
        // Optional. The domain name that is used to access OSS.
        let endpoint: String? = nil

        // Specify the AccessKey ID and AccessKey secret of the temporary access credential that you obtained, not the AccessKey ID and AccessKey secret of your Alibaba Cloud account.
        // The AccessKey ID obtained from STS starts with STS., as shown in the following example.
        let accessKeyId = "STS.L4aBSCSJVMuKg5U1****"
        let accessKeySecret = "yourAccessKeySecret"
        let securityToken = "yourSecurityToken"

        // Use StaticCredentialsProvider to directly specify the accessKeyId, accessKeySecret, and securityToken.
        let credentialsProvider = StaticCredentialsProvider(accessKeyId: accessKeyId,
                                                            accessKeySecret: accessKeySecret,
                                                            securityToken: securityToken)

        // Configure the parameters of the OSS client.
        let config = Configuration.default()
            .withRegion(region)        // Specify the region in which the bucket is located.
            .withCredentialsProvider(credentialsProvider)  // Specify the access credentials.

        // Specify a custom endpoint.
        if let endpoint = endpoint {
            config.withEndpoint(endpoint)
        }

        // Create an OSS client instance.
        let client = Client(config)

        // Use the client to make requests on objects, such as uploading, downloading, or managing objects.
    }
}

Custom credential provider

If none of the preceding credential configuration methods meet your requirements, you can customize how credentials are obtained. OSS SDK for Swift supports multiple implementation methods.

Use the ClosureCredentialsProvider interface

Implement the ClosureCredentialsProvider interface to customize how credentials are obtained.

import AlibabaCloudOSS
import Foundation

@main
struct Main {
    static func main() async {
        // The region in which the bucket is located. Example: cn-hangzhou.
        let region = "cn-hangzhou"
        // Optional. The domain name that is used to access OSS.
        let endpoint: String? = nil

        // Method 1: Obtain long-term access credentials.
        let credentialsProvider = ClosureCredentialsProvider {
            // TODO
            // You can customize how long-term access credentials are obtained.

            // Assume that the following values are obtained.
            let accessKeyId = "yourAccessKeyID"
            let accessKeySecret = "yourAccessKeySecret"

            // Return the long-term access credentials.
            return Credentials(accessKeyId: accessKeyId,
                        accessKeySecret: accessKeySecret)
        }

        // Method 2: Obtain temporary credentials.
        // let credentialsProvider = ClosureCredentialsProvider {
             // TODO
            // You can customize how temporary access credentials are obtained.

            // Assume that the following values are obtained.
            // let accessKeyId = "yourAccessKeyID"
            // let accessKeySecret = "yourAccessKeySecret"
            // let securityToken = "yourSecurityToken"

        // Return the temporary access credentials.
        //  return Credentials(accessKeyId: accessKeyId,
        //               accessKeySecret: accessKeySecret,
        //                securityToken: securityToken)
        // }

        // Configure the parameters of the OSS client.
        let config = Configuration.default()
            .withRegion(region)        // Specify the region in which the bucket is located.
            .withCredentialsProvider(credentialsProvider)  // Specify the access credentials.

        // Specify a custom endpoint.
        if let endpoint = endpoint {
            config.withEndpoint(endpoint)
        }

        // Create an OSS client instance.
        let client = Client(config)

        // Use the client to make requests on objects, such as uploading, downloading, or managing objects.
    }
}

Use the RefreshCredentialsProvider interface

Use the RefreshCredentialsProvider interface to customize the logic that obtains and automatically refreshes access credentials. This mechanism supports two modes:

  • No automatic refresh — If you do not specify an expiration time (expiration) in the credential closure, access credentials are not automatically refreshed.

  • Automatic refresh — If you specify an expiration time (expiration) in the closure, the RefreshCredentialsProvider interface periodically calls the closure to update access credentials based on the refresh interval (refreshInterval) and the expiration time.

import AlibabaCloudOSS
import Foundation

@main
struct Main {
    static func main() async {
        // The region in which the bucket is located. Example: cn-hangzhou.
        let region = "cn-hangzhou"
        // Optional. The domain name that is used to access OSS.
        let endpoint: String? = nil

        // Access credentials that are automatically refreshed based on the expiration time.
        // refreshInterval: the refresh interval, in seconds. Default value: 300.
        let credentialsProvider = RefreshCredentialsProvider(refreshInterval: 500) {

            // You can customize how temporary credentials are obtained here.

            // TODO......

            // Assume that the following values are obtained.
            let accessKeyId = "yourAccessKeyID"
            let accessKeySecret = "yourAccessKeySecret"
            let securityToken = "yourSecurityToken"

            // You can specify an expiration time. This is optional.
            // If you do not specify an expiration time, access credentials are not automatically refreshed.
            // Replace Date() with the actual expiration time of the credentials. If you specify an expiration time, the closure is called periodically based on the refreshInterval and the expiration time to refresh the credentials.
            let expiration = Date()

            // Return the access credential object.
            return Credentials(accessKeyId: accessKeyId,
                               accessKeySecret: accessKeySecret,
                               securityToken: securityToken,
                               expiration: expiration)
        }

        // Configure the parameters of the OSS client.
        let config = Configuration.default()
            .withRegion(region)        // Specify the region in which the bucket is located.
            .withCredentialsProvider(credentialsProvider)  // Specify the access credentials.

        // Specify a custom endpoint.
        if let endpoint = endpoint {
            config.withEndpoint(endpoint)
        }

        // Create an OSS client instance.
        let client = Client(config)

        // Use the client to make requests on objects, such as uploading, downloading, or managing objects.
    }
}

FAQ

How can I distinguish between temporary access credentials provided by STS and the AccessKey pair of a RAM user when I initialize a credential provider?

When you use temporary access credentials (AccessKey ID, AccessKey secret, and STS token) obtained from STS to initialize a credential provider, do not confuse the AccessKey ID returned by STS with the AccessKey ID of the RAM user. The AccessKey ID obtained from STS starts with STS. Example:

image

How do I view the AccessKey ID of a RAM user? Can I view the AccessKey secret of an AccessKey pair?

  1. You can view the AccessKey pair of a RAM user by following steps described in View RAM user AccessKey information.

  2. The AccessKey secret of a RAM user is displayed only when the AccessKey pair is created. You cannot view the AccessKey pair at a later time. If you forget the AccessKey secret, you cannot retrieve the AccessKey secret. In this case, you can directly create a new AccessKey pair for rotation in the RAM console. For more information, see Create an AccessKey.

How do I fix an AccessDenied error that occurs when I use the AccessKey pair of a RAM user to upload files?

The AccessDenied error occurs typically for two reasons: wrong AccessKey pair or a lack of upload permissions. You can perform the following steps to troubleshoot the AccessDenied error:

  1. Check whether the provided AccessKey pair is correct by following the instructions described in View RAM user AccessKey information.

  2. The AccessKey secret of a RAM user is displayed only when the AccessKey pair is created. You cannot view the AccessKey pair at a later time. If you forget the AccessKey secret, you cannot retrieve the AccessKey secret. In this case, you can directly create a new AccessKey pair for rotation in the RAM console. For more information, see Create an AccessKey.

  3. In the RAM console, check whether the RAM user has the permission to upload files to OSS. If not, grant the required permissions.

How do I fix a connection error when I access OSS by using a public OSS endpoint?

If you encounter a connection error when accessing OSS over the public endpoint, it may be due to an incorrect endpoint. To fix the error, perform the following checks:

  1. Check the region of the bucket in the OSS console.

  2. Check whether the specified endpoint is the correct one for the region. For example, if the bucket is located in the China(Hangzhou) region, use the oss-cn-hangzhou.aliyuncs.com endpoint to enable public network access. For a list of OSS endpoints, see Regions and endpoints.

  3. Check whether your environment can connect to the Internet.

If an error is reported, how do I determine the type of the error?

OSS provides error codes to help you determine the specific type of an error. For example, you can see 02-AUTH for common authentication errors.