Configure access credentials (Swift SDK)

更新时间:
复制 MD 格式

To make requests to Object Storage Service (OSS) using the Swift SDK, you must configure credentials. Alibaba Cloud services use these credentials to verify your identity and permissions. Choose a credential type that meets your use case's authentication and authorization requirements.

Prerequisites

Choose a credential provider

OSS allows you to initialize a credential provider in different ways. Choose an initialization method that meets your use case's authentication and authorization requirements.

Provider

Best for

Pre-configuration required

Credential type

Validity

Rotation or refresh

Use the AccessKey of a RAM user

Secure backend environments that require long-term, stable access without frequent rotation.

Yes

AccessKey

Long-term

Manual rotation

Use an STS temporary credential

Untrusted environments where you need to control access duration and permissions.

Yes

STS token

Temporary

Manual refresh

Custom credential provider

Customize credential acquisition if the built-in providers do not meet your requirements.

Custom

Custom

Custom

Custom

Common configuration examples

Use the AccessKey of a RAM user

If your application runs in a secure, stable environment that requires long-term access to OSS without the need for frequent credential rotation, you can use the AccessKey (AccessKey ID and AccessKey secret) of an Alibaba Cloud root account or a RAM user to initialize a credential provider. This method requires manual AccessKey maintenance, which increases security risks and operational overhead.

Warning
  • Never use the AccessKey of your Alibaba Cloud root account. It has unrestricted access to all your resources and poses a high security risk if leaked. Instead, create a RAM user with only the permissions your application needs.

  • To create an AccessKey for a RAM user, see Create an AccessKey. The AccessKey ID and AccessKey secret are shown only when the pair is created. Save them immediately. If you lose them, you must create a new AccessKey pair and rotate your credentials.

Environment variables

  1. Configure environment variables using the AccessKey of a 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. After modifying the system environment variables, restart or refresh your build and runtime environment, including your IDE, command-line interface, other desktop applications, and background services, to load the updates.

  3. Use environment variables to pass credential information.

    import AlibabaCloudOSS
    import Foundation
    
    @main
    struct Main {
        static func main() async {
            // Specify the region where your bucket is located, for example, cn-hangzhou for China (Hangzhou).
            let region = "cn-hangzhou"
            // Optional. Specify the domain name to access OSS. For example, if the region is China (Hangzhou), set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
            let endpoint: String? = nil
    
            // Obtain 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 set.
            let credentialsProvider = EnvironmentCredentialsProvider()
    
            // Configure OSS client parameters.
            let config = Configuration.default()
                .withRegion(region)        // Set the region where the bucket is located.
                .withCredentialsProvider(credentialsProvider)  // Set the credentials.
                
            // Set a custom endpoint.
            if let endpoint = endpoint {
                config.withEndpoint(endpoint)
            }
            
            // Create an OSS client instance.
            let client = Client(config)
            
            // Use the client to send requests, such as to upload, download, or manage objects.
        }
    }

Static credentials

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

Warning

Never embed credentials directly in production code. This approach is for local testing only.

import AlibabaCloudOSS
import Foundation

@main
struct Main {
    static func main() async {
        // Specify the region where your bucket is located, for example, cn-hangzhou for China (Hangzhou).
        let region = "cn-hangzhou"
        // Optional. Specify the domain name to access OSS. For example, if the region is China (Hangzhou), set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
        let endpoint: String? = nil

        // Specify the AccessKey ID and AccessKey secret of the RAM user.
        let accessKeyId = "yourAccessKeyID"
        let accessKeySecret = "yourAccessKeySecret"
        
        // Use the StaticCredentialsProvider method to directly set the accessKeyId and accessKeySecret.
        let credentialsProvider = StaticCredentialsProvider(accessKeyId: accessKeyId,
                                                            accessKeySecret: accessKeySecret)

        // Configure OSS client parameters.
        let config = Configuration.default()
            .withRegion(region)        // Set the region where the bucket is located.
            .withCredentialsProvider(credentialsProvider)  // Set the credentials.
            
        // Set a custom endpoint.
        if let endpoint = endpoint {
            config.withEndpoint(endpoint)
        }
        
        // Create an OSS client instance.
        let client = Client(config)
        
        // Use the client to send requests, such as to upload, download, or manage objects.
    }
}

Use an STS temporary credential

If your application requires temporary access to OSS, you can initialize a credential provider using a temporary credential (AccessKey ID, AccessKey secret, and security token) obtained from Security Token Service (STS). This method requires manual STS token maintenance and refresh, increasing security risks and operational overhead.

Important

Environment variables

  1. Set environment variables using a temporary credential.

    macOS and Linux

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

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

    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

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

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

    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>
  2. Use environment variables to pass credential information.

    import AlibabaCloudOSS
    import Foundation
    
    @main
    struct Main {
        static func main() async {
            // Specify the region where your bucket is located, for example, cn-hangzhou for China (Hangzhou).
            let region = "cn-hangzhou"
            // Optional. Specify the domain name to access OSS. For example, if the region is China (Hangzhou), set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
            let endpoint: String? = nil
    
            // Obtain 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 set.
            let credentialsProvider = EnvironmentCredentialsProvider()
    
            // Configure OSS client parameters.
            let config = Configuration.default()
                .withRegion(region)        // Set the region where the bucket is located.
                .withCredentialsProvider(credentialsProvider)  // Set the credentials.
                
            // Set a custom endpoint.
            if let endpoint = endpoint {
                config.withEndpoint(endpoint)
            }
            
            // Create an OSS client instance.
            let client = Client(config)
            
            // Use the client to send requests, such as to upload, download, or manage objects.
        }
    }

Static credentials

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

Warning

Never embed credentials directly in production code. This approach is for local testing only.

import AlibabaCloudOSS
import Foundation

@main
struct Main {
    static func main() async {
        // Specify the region where your bucket is located, for example, cn-hangzhou for China (Hangzhou).
        let region = "cn-hangzhou"
        // Optional. Specify the domain name to access OSS. For example, if the region is China (Hangzhou), set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
        let endpoint: String? = nil

        // Specify the temporary AccessKey ID, AccessKey secret, and security token that you obtained. Do not use the AccessKey ID and AccessKey secret of an Alibaba Cloud account.
        // The AccessKey ID obtained from STS starts with "STS.".
        let accessKeyId = "yourAccessKeyID"
        let accessKeySecret = "yourAccessKeySecret"
        let securityToken = "yourSecurityToken"
        
        // Use the StaticCredentialsProvider method to directly set the AccessKey ID, AccessKey secret, and security token.
        let credentialsProvider = StaticCredentialsProvider(accessKeyId: accessKeyId,
                                                            accessKeySecret: accessKeySecret,
                                                            securityToken: securityToken)

        // Configure OSS client parameters.
        let config = Configuration.default()
            .withRegion(region)        // Set the region where the bucket is located.
            .withCredentialsProvider(credentialsProvider)  // Set the credentials.
            
        // Set a custom endpoint.
        if let endpoint = endpoint {
            config.withEndpoint(endpoint)
        }
        
        // Create an OSS client instance.
        let client = Client(config)
        
        // Use the client to send requests, such as to upload, download, or manage objects.
    }
}

Advanced configuration

Custom credential provider

If the built-in credential providers do not meet your requirements, you can implement a custom one. The SDK provides multiple ways to do this.

  1. Use the ClosureCredentialsProvider interface

You can implement the ClosureCredentialsProvider interface to customize how credentials are obtained.

import AlibabaCloudOSS
import Foundation

@main
struct Main {
    static func main() async {
        // Specify the region where your bucket is located, for example, cn-hangzhou for China (Hangzhou).
        let region = "cn-hangzhou"
        // Optional. Specify the domain name to access OSS. For example, if the region is China (Hangzhou), set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
        let endpoint: String? = nil
        
        // Method 1: Obtain a long-term credential.
        let credentialsProvider = ClosureCredentialsProvider {
            // TODO
            // Add your custom method to obtain long-term credentials.
            
            // Assume that the following values are obtained.
            let accessKeyId = "yourAccessKeyID"
            let accessKeySecret = "yourAccessKeySecret"
            
            // Return a long-term credential.
            return Credentials(accessKeyId: accessKeyId,
                        accessKeySecret: accessKeySecret)
        }
        
        // Method 2: Obtain a temporary credential.
        // let credentialsProvider = ClosureCredentialsProvider {
             // TODO
            // Add your custom method to obtain temporary credentials.
        
            // Assume that the following values are obtained.
            // let accessKeyId = "yourAccessKeyID"
            // let accessKeySecret = "yourAccessKeySecret"
            // let securityToken = "yourSecurityToken"
            
        // Return a temporary credential.
        //  return Credentials(accessKeyId: accessKeyId,
        //               accessKeySecret: accessKeySecret,
        //                securityToken: securityToken)
        // }

        // Configure OSS client parameters.
        let config = Configuration.default()
            .withRegion(region)        // Set the region where the bucket is located.
            .withCredentialsProvider(credentialsProvider)  // Set the credentials.
            
        // Set a custom endpoint.
        if let endpoint = endpoint {
            config.withEndpoint(endpoint)
        }
        
        // Create an OSS client instance.
        let client = Client(config)
        
        // Use the client to send requests, such as to upload, download, or manage objects.
    }
}
  1. Use the RefreshCredentialsProvider interface

You can use the RefreshCredentialsProvider interface to customize the logic for obtaining and automatically refreshing credentials. This mechanism supports two modes:

  • Disable automatic credential refresh: Do not set an expiration time (expiration) in the credential closure function.

  • Enable automatic credential refresh: Set an expiration time (expiration) in the closure function. The RefreshCredentialsProvider then periodically calls the closure to update the credentials based on the refreshInterval value and the expiration time.

import AlibabaCloudOSS
import Foundation

@main
struct Main {
    static func main() async {
        // Specify the region where your bucket is located, for example, cn-hangzhou for China (Hangzhou).
        let region = "cn-hangzhou"
        // Optional. Specify the domain name to access OSS. For example, if the region is China (Hangzhou), set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
        let endpoint: String? = nil

        // Automatically refresh credentials based on the expiration time.
        // refreshInterval: the refresh interval. Default value: 300. Unit: seconds.
        let credentialsProvider = RefreshCredentialsProvider(refreshInterval: 500) {
        
            // You can add your custom method to obtain temporary credentials here.

            // TODO......

            // Assume that the following values are obtained.
            let accessKeyId = "yourAccessKeyID"
            let accessKeySecret = "yourAccessKeySecret"
            let securityToken = "yourSecurityToken"
            
            // Optional: set the expiration time.
            // If you do not set an expiration time, credentials are not automatically refreshed.
            let expiration = Date() // If you set an expiration time, the closure is periodically called to refresh credentials based on the refreshInterval value and the expiration time.
            
            // Return a credential object.
            return Credentials(accessKeyId: accessKeyId,
                               accessKeySecret: accessKeySecret,
                               securityToken: securityToken,
                               expiration: expiration)
        }

        // Configure OSS client parameters.
        let config = Configuration.default()
            .withRegion(region)        // Set the region where the bucket is located.
            .withCredentialsProvider(credentialsProvider)  // Set the credentials.
            
        // Set a custom endpoint.
        if let endpoint = endpoint {
            config.withEndpoint(endpoint)
        }
        
        // Create an OSS client instance.
        let client = Client(config)
        
        // Use the client to send requests, such as to upload, download, or manage 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 AccessKey pair details.

  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 pair.

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 AccessKey pair details.

  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 pair.

  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.