Configure access credentials for OSS SDK for Swift
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
AlibabaCloudOSSmodule.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-hangzhoufor China (Hangzhou). The endpoint is optional: specify it only to send requests to a specific domain name, such ashttps://oss-cn-hangzhou.aliyuncs.comfor 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 method | Scenarios | Requires an existing AccessKey or Security Token Service (STS) token | Underlying credential type | Credential validity period | Credential rotation or refresh method |
| Use the AccessKey of a RAM user | Applications 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. | Yes | AccessKey | Long-term | Manual rotation |
| Use an STS temporary access credential | Applications that run in an untrusted environment and that require control over the validity period and permissions of access. | Yes | STS token | Temporary | Manual refresh |
| Custom credential provider | Applications that require a credential source that the preceding methods do not cover. | Depends on your implementation | Custom | Custom | Custom |
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
StaticCredentialsProviderdirectly. 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.
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
Configure the
OSS_ACCESS_KEY_IDandOSS_ACCESS_KEY_SECRETenvironment variables with the AccessKey ID and AccessKey secret of the 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)
-
-
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.
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.
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.
To quickly obtain a temporary STS access credential by using OpenAPI, see AssumeRole - Obtain temporary identity credentials for a role.
To obtain a temporary STS access credential by using an SDK, see Use an STS temporary access credential to access OSS.
Specify an expiration time when you generate an STS token. After the STS token expires, it automatically becomes invalid and cannot be used. To refresh temporary credentials automatically instead of manually, see Use the RefreshCredentialsProvider interface.
For the list of STS endpoints, see Service endpoints.
Environment variables
Configure the environment variables with the temporary credentials that you obtained from STS.
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.
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, theRefreshCredentialsProviderinterface 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.
}
}