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
For information about the mappings between regions and endpoints that are supported by OSS, see regions and endpoints.
To create an AccessKey for a RAM user, see Create an AccessKey.
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 |
Secure backend environments that require long-term, stable access without frequent rotation. | Yes | AccessKey | Long-term | Manual rotation | |
Untrusted environments where you need to control access duration and permissions. | Yes | STS token | Temporary | Manual refresh | |
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.
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
Configure environment variables using the AccessKey of a RAM user.
Linux
-
Run the following commands on the CLI to add the configurations of the environment variables to the
~/.bashrcfile:echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc-
Apply the changes.
source ~/.bashrc -
Check whether the environment variables have taken effect:
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
macOS
-
Run the following command in the terminal to view the default shell type:
echo $SHELL-
Configure environment variables based on the default shell type.
Zsh
-
Run the following commands to add the configurations of the environment variables to the
~/.zshrcfile:echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc -
Apply the changes.
source ~/.zshrc -
Check whether the environment variables have taken effect:
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Bash
-
Run the following commands to add the configurations of the environment variables to the
~/.bash_profilefile:echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile -
Apply the changes.
source ~/.bash_profile -
Check whether the environment variables have taken effect:
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
-
Windows
CMD
-
Run the following commands in CMD:
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"-
Check whether the environment variables take effect:
echo %OSS_ACCESS_KEY_ID% echo %OSS_ACCESS_KEY_SECRET%
-
PowerShell
-
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)-
Check whether the environment variable takes effect:
[Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
-
-
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.
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.
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.
To quickly obtain an STS temporary credential using OpenAPI, see AssumeRole - Obtain a temporary credential for a role.
To obtain an STS temporary credential using an SDK, see Use an STS temporary credential to access OSS.
An expiration time must be specified when an STS token is generated. After the STS token expires, it becomes invalid.
For a list of endpoints for the STS service, see Service endpoints.
Environment variables
Set environment variables using a temporary credential.
macOS and Linux
WarningThe 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
WarningThe 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>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.
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.
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.
}
}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.
}
}