To use Object Storage Service (OSS) SDK for Java to initiate a request, you must configure access credentials, which are used to verify your identity and access permissions. You can select different types of access credentials based on your authentication and authorization requirements.
Credential provider initialization
OSS supports multiple methods to initialize a credential provider. You can select a suitable method based on your actual authentication and authorization requirements.
Initialization method | Scenario | AccessKey pair or STS token required | Underlying credential | Credential validity period | Credential rotation or refresh method |
Initialization method | Scenario | AccessKey pair or STS token required | Underlying credential | Credential validity period | Credential rotation or refresh method |
Use the AccessKey pair of a RAM user | Applications are deployed and run in a secure and stable environment that is not vulnerable to external attacks, and need long-term access to cloud services without frequent credential rotation. | Yes | AK | Long-term | Manual rotation |
Use temporary access credentials provided by STS | Applications are deployed and run in an untrusted environment, in which case you want to manage the credential validity and the resources that can be accessed. | Yes | STS Token | Temporary | Manual refresh |
Use the ARN of a RAM role | Applications require access to cloud services, such as cross-account access. | Yes | STS Token | Temporary | Automatic refresh |
Use the RAM role of an ECS instance | Applications are deployed and run on Elastic Compute Service (ECS) instances, Elastic Container Instance, or Container Service for Kubernetes (ACK) worker nodes. | No | STS Token | Temporary | Automatic refresh |
Use the RAM role of an OIDC IdP | Untrusted applications are deployed and run on ACK worker nodes. | No | STS Token | Temporary | Automatic refresh |
Use the Credentials parameter in the context of Function Compute | Functions of your applications are deployed and run in Function Compute. | No | STS Token | Temporary | No need to refresh |
Use credentials URIs | Applications require access credentials from external systems. | No | STS Token | Temporary | Automatic refresh |
Use an AccessKey pair that automatically rotates | Applications are deployed in an environment where AccessKey pairs are at a high risk of leakage, and require frequent rotation of access credentials to gain long-term access to cloud services. | No | AK | Long-term | Automatic rotation |
Use custom access credentials | If none of the preceding methods meet your requirements, you can use a custom method to obtain access credentials. | Custom | Custom | Custom | Custom |
Use the default credential provider chain | If you do not specify a method to initialize a Credentials client, the default credential provider chain is used. | No | Custom | Custom | Automatic refresh |
Commonly used configuration example
Use the AccessKey pair of a RAM user
Assume that your application requires long-term access to OSS without frequently rotating access credentials and runs in a secure and stable environment that is not vulnerable to external attacks. In this case, you can use an AccessKey pair (an AccessKey ID and an AccessKey secret) of your Alibaba Cloud account or a RAM user to initialize a credential provider. Take note that this method requires you to manually maintain an AccessKey pair. This poses security risks and increases maintenance complexity.
Warning
An Alibaba Cloud account has full permissions on its resources, and leaks of its AccessKey pair pose significant security risks. Therefore, we recommend that you use the AccessKey pair of a RAM user with the minimum required permissions to initialize a credential provider.
For information about how to create an AccessKey pair for a RAM user, see Create an AccessKey pair for a RAM user. The AccessKey pair of a RAM user is displayed only when the RAM user is created. Save the AccessKey pair in a timely manner. If you forget the AccessKey pair, create a new AccessKey pair for rotation.
Environment variables
Configure environment variables for the AccessKey pair.
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
Run the following command to apply the changes:
Run the following commands to check whether the environment variables take effect:
echo $OSS_ACCESS_KEY_ID
echo $OSS_ACCESS_KEY_SECRET
Run the following command in the terminal to view the default shell type:
Configure environment variables based on the default shell type.
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
Run the following command to apply the changes:
Run the following commands to check whether the environment variables take effect:
echo $OSS_ACCESS_KEY_ID
echo $OSS_ACCESS_KEY_SECRET
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
Run the following command to apply the changes:
Run the following commands to check whether the environment variables take effect:
echo $OSS_ACCESS_KEY_ID
echo $OSS_ACCESS_KEY_SECRET
Run the following commands in CMD:
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
Run the following commands to check whether the environment variables take effect:
echo %OSS_ACCESS_KEY_ID%
echo %OSS_ACCESS_KEY_SECRET%
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)
Run the following commands to check whether the environment variable takes effect:
[Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
[Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
Pass credentials by using environment variables.
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
public class AkDemoTest {
public static void main(String[] args) throws Exception {
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint("endpoint")
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region("region")
.build();
ossClient.shutdown();
}
}
Static credentials
You can define credentials by using variables in your code. During the code execution, these variables are populated with actual credential values sourced from environment variables, configuration files, or other external locations.
The following procedure describes how to use a configuration file to provide credentials.
Create a configuration file named config.ini
.
[credentials]
alibaba_cloud_access_key_id = <ALIBABA_CLOUD_ACCESS_KEY_ID>
alibaba_cloud_access_key_secret = <ALIBABA_CLOUD_ACCESS_KEY_SECRET>
Pass credentials by using the configuration file.
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import java.io.FileInputStream;
import java.util.Properties;
public class AkDemoTest {
public static void main(String[] args) throws Exception {
Properties properties = new Properties();
String configFilePath = "config.ini";
FileInputStream input = new FileInputStream(configFilePath);
properties.load(input);
input.close();
String accessKeyId = properties.getProperty("alibaba_cloud_access_key_id");
String accessKeySecret = properties.getProperty("alibaba_cloud_access_key_secret");
CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint("endpoint")
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region("region")
.build();
ossClient.shutdown();
}
}
Use temporary access credentials provided by STS
If your application needs to access OSS temporarily, you can use temporary access credentials provided by Security Token Service (STS), which consist of an AccessKey pair and an STS token. Take note that this method requires you to manually maintain an STS token. This poses security risks and increases maintenance complexity. If you want to access OSS multiple times, you must manually refresh the STS token.
Important
You can obtain temporary access credentials by calling the AssumeRole API operation. For more information, see AssumeRole.
You can also obtain temporary access credentials by using the SDK. For more information, see Use temporary access credentials provided by STS to access OSS.
You must specify a validity period for the STS token when you generate the token. An expired STS token cannot be used.
For a list of STS endpoints, see Endpoints.
Environment variables
Configure environment variables for temporary access credentials.
Mac OS X/Linux/Unix
Windows
Warning
Note that the temporary access credentials (AccessKey ID, AccessKey secret, and STS token) provided by STS are used instead of the AccessKey pair (AccessKey ID and AccessKey secret) of the RAM user.
The AccessKey ID provided by STS starts with STS. Example: STS.L4aBSCSJVMuKg5U1****.
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>
Warning
Note that the temporary access credentials (AccessKey ID, AccessKey secret, and STS token) provided by STS are used instead of the AccessKey pair (AccessKey ID and AccessKey secret) of the RAM user.
The AccessKey ID provided by STS starts with STS. Example: STS.L4aBSCSJVMuKg5U1****.
set OSS_ACCESS_KEY_ID=<ALIBABA_CLOUD_ACCESS_KEY_ID>
set OSS_ACCESS_KEY_SECRET=<ALIBABA_CLOUD_ACCESS_KEY_SECRET>
set OSS_SESSION_TOKEN=<ALIBABA_CLOUD_SECURITY_TOKEN>
Pass credential information by using environment variables.
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
public class StsDemoTest {
public static void main(String[] args) throws Exception {
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint("endpoint")
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region("region")
.build();
ossClient.shutdown();
}
}
Static credentials
You can hardcode the static credentials in your application to explicitly specify the AccessKey pair that you want to use to access OSS.
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
public class StsDemoTest {
public static void main(String[] args) throws Exception {
String accessKeyId = "STS.NTZdStF79CVRTQuWCfXTT****"
String accessKeySecret = "5rm8PfEiK8enp56zzAMX4RbZUraoKbWXvCf1xAuT****"
String stsToken= "********"
CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret, stsToken);
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint("endpoint")
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region("region")
.build();
ossClient.shutdown();
}
}
Configuration examples for other scenarios
Use the ARN of a RAM role
If you need to authorize your application to access OSS, for example, when your application requires access to OSS resources of another Alibaba Cloud account, you can use RAMRoleARN to initialize a credential provider. The underlying logic of this method is to use an STS token obtained from STS to configure access credentials. The Credentials tool obtains an STS token based on the RAM role identified by the ARN of the RAM role and refreshes the STS token by calling the AssumeRole operation before the session expires. You can specify a policy
to limit the permissions granted to the RAM role.
Important
An Alibaba Cloud account has full permissions on its resources, and leaks of its AccessKey pair pose significant security risks. Therefore, we recommend that you use the AccessKey pair of a RAM user with the minimum required permissions to initialize a credential provider.
For information about how to create an AccessKey pair for a RAM user, see Create an AccessKey pair for a RAM user. The AccessKey pair of a RAM user is displayed only when the RAM user is created. Save the AccessKey pair in a timely manner. If you forget the AccessKey pair, create a new AccessKey pair for rotation.
You can create a RAM role by calling the CreateRole operation. For more information, see CreateRole.
Add the credentials dependency.
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>credentials-java</artifactId>
<version>LATEST</version>
</dependency>
Configure the AccessKey pair and RAMROLEARN as access credentials.
import com.aliyun.credentials.models.CredentialModel;
import com.aliyun.oss.common.auth.Credentials;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentials;
public class RamRoleArnAkDemoTest {
public static void main(String[] args) {
com.aliyun.credentials.models.Config config = new com.aliyun.credentials.models.Config();
config.setType("ram_role_arn");
config.setRoleArn("<RoleArn>");
config.setAccessKeyId(System.getenv().get("ALIBABA_CLOUD_ACCESS_KEY_ID"));
config.setAccessKeySecret(System.getenv().get("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
config.setRoleName("<RoleSessionName>");
config.setPolicy("<Policy>");
config.setRoleSessionExpiration(3600);
final com.aliyun.credentials.Client credentialsClient = new com.aliyun.credentials.Client(config);
CredentialsProvider credentialsProvider = new CredentialsProvider(){
@Override
public void setCredentials(Credentials credentials) {
}
@Override
public Credentials getCredentials() {
CredentialModel credential = credentialsClient.getCredential();
return new DefaultCredentials(credential.getAccessKeyId(), credential.getAccessKeySecret(), credential.getSecurityToken());
}
};
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint("endpoint")
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region("region")
.build();
ossClient.shutdown();
}
}
Use the RAM role of an ECS instance
If your application runs on an ECS instance, an elastic container instance, or an ACK worker node, we recommend that you use ECSRAMRole to initialize a credential provider. The underlying logic of this method is to use an STS token obtained from STS to configure access credentials. ECSRAMRole allows you to attach a RAM role to an ECS instance, an elastic container instance, or an ACK worker node to automatically refresh the STS token on the instance. This method does not require an AccessKey pair or STS token, eliminating the risks associated with manually managing these credentials. You can create a RAM role by calling the CreateRole operation. The ARN is included in the response. For more information, see CreateRole. For information about how to attach a RAM role to an ECS instance, see Instance RAM roles.
Add the credentials dependency.
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>credentials-java</artifactId>
<version>LATEST</version>
</dependency>
Use the RAM role to provide access credentials.
import com.aliyun.credentials.models.CredentialModel;
import com.aliyun.oss.common.auth.Credentials;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentials;
public class EcsRamRoleDemoTest {
public static void main(String[] args) {
com.aliyun.credentials.models.Config config = new com.aliyun.credentials.models.Config();
config.setType("ecs_ram_role");
config.setRoleName("<RoleName>");
final com.aliyun.credentials.Client credentialsClient = new com.aliyun.credentials.Client(config);
CredentialsProvider credentialsProvider = new CredentialsProvider(){
@Override
public void setCredentials(Credentials credentials) {
}
@Override
public Credentials getCredentials() {
CredentialModel credential = credentialsClient.getCredential();
return new DefaultCredentials(credential.getAccessKeyId(), credential.getAccessKeySecret(), credential.getSecurityToken());
}
};
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint("endpoint")
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region("region")
.build();
ossClient.shutdown();
}
}
Use the RAM role of an OIDC IdP
After the RAM role is configured on the ACK worker node, the application in a pod on the corresponding node can obtain the STS token of the attached role by using the metadata server in the same manner as an application deployed on an ECS instance does. However, if an untrusted application is deployed on the worker node, such as an application that is submitted by your customer and whose code is unavailable to you, you may not want the application to use the metadata server to obtain an STS token of the RAM role attached to the worker node. To ensure the security of cloud resources, allow untrusted applications to securely obtain the required STS token, and minimize application-level permissions, you can use the RAM Roles for Service Account (RRSA) feature. The underlying logic of this method is to use an STS token obtained from STS to configure access credentials. ACK creates and mounts corresponding OpenID Connect (OIDC) token files for different application pods, and passes relevant configuration information to environment variables. The Credentials tool obtains the configuration information from the environment variables and calls the AssumeRoleWithOIDC operation of STS to obtain the STS token of attached roles. This method does not require an AccessKey pair or STS token, eliminating the risks associated with manually managing these credentials. For more information, see Use RRSA to authorize different pods to access different cloud services.
Add the credentials dependency.
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>credentials-java</artifactId>
<version>LATEST</version>
</dependency>
Use the RAM role for OIDC IdP to provide access credentials.
import com.aliyun.credentials.models.CredentialModel;
import com.aliyun.oss.common.auth.Credentials;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentials;
public class OidcRoleArnDemoTest {
public static void main(String[] args) {
com.aliyun.credentials.models.Config config = new com.aliyun.credentials.models.Config();
config.setType("oidc_role_arn");
config.setRoleArn("<RoleArn>");
config.setOidcProviderArn("<OidcProviderArn>");
config.setOidcTokenFilePath("<OidcTokenFilePath>");
config.setRoleSessionName("<RoleSessionName>");
config.setPolicy("<Policy>");
config.setRoleSessionExpiration(3600);
final com.aliyun.credentials.Client credentialsClient = new com.aliyun.credentials.Client(config);
CredentialsProvider credentialsProvider = new CredentialsProvider(){
@Override
public void setCredentials(Credentials credentials) {
}
@Override
public Credentials getCredentials() {
CredentialModel credential = credentialsClient.getCredential();
return new DefaultCredentials(credential.getAccessKeyId(), credential.getAccessKeySecret(), credential.getSecurityToken());
}
};
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint("endpoint")
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region("region")
.build();
ossClient.shutdown();
}
}
Use Credentials in the context of Function Compute
If the function of your application is deployed and run in Function Compute, you can initialize the credential provider by using Credentials in the context of Function Compute context. The underlying logic of this method is to use an STS token obtained from STS to configure access credentials. Function Compute obtains an STS token by assuming a service role based on the role configured for the function. Then, the STS token is passed to your application by using Credentials in the context. The STS token is valid for 36 hours. You cannot change its validity period. A function can execute for up to 24 hours. You do not need to refresh the STS token during function execution, because it remains valid throughout the execution of the function. This method does not require an AccessKey pair or STS token, eliminating the risks associated with manually managing these credentials. For more information about how to authorize Function Compute to access OSS, see Grant Function Compute permissions to access other Alibaba Cloud services.
Add Function Compute context dependency.
<dependency>
<groupId>com.aliyun.fc.runtime</groupId>
<artifactId>fc-java-core</artifactId>
<version>1.4.1</version>
</dependency>
Initializes the credential provider by using Credentials in the Function Compute context.
package example;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.aliyun.fc.runtime.Context;
import com.aliyun.fc.runtime.Credentials;
import com.aliyun.fc.runtime.StreamRequestHandler;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
public class App implements StreamRequestHandler {
@Override
public void handleRequest(
InputStream inputStream, OutputStream outputStream, Context context) throws IOException {
Credentials creds = context.getExecutionCredentials();
CredentialsProvider credentialsProvider = new DefaultCredentialProvider(creds.getAccessKeyId(), creds.getAccessKeySecret(), creds.getSecurityToken());
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint("endpoint")
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region("region")
.build();
ossClient.shutdown();
outputStream.write(new String("done").getBytes());
}
}
Use credentials URIs
If your application needs to obtain Alibaba Cloud credentials from an external system to implement flexible credential management and keyless access, you can use the CredentialsURI to initialize a credential provider. The underlying logic of this method is to use an STS token obtained from STS to configure access credentials. The Credentials tool obtains the STS token by using the URI that you specify to initialize the client. This method does not require an AccessKey pair or STS token, eliminating the risks associated with manually managing these credentials.
Important
Note that the CredentialsURI refers to the address of the server that generates an STS token.
The backend service that provides the credentials URI response must automatically refresh the STS token to ensure that your application can always obtain valid credentials.
To allow the Credentials tool to correctly parse and use an STS token, the URI must comply with the following requirements:
Add the credentials dependency.
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>credentials-java</artifactId>
<version>LATEST</version>
</dependency>
Configure the credential URI as the access credential.
import com.aliyun.credentials.models.CredentialModel;
import com.aliyun.oss.common.auth.Credentials;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentials;
public class CredentialsUriDemoTest {
public static void main(String[] args) {
com.aliyun.credentials.models.Config config = new com.aliyun.credentials.models.Config();
config.setType("credentials_uri");
config.setCredentialsUri("<CredentialsUri>");
final com.aliyun.credentials.Client credentialsClient = new com.aliyun.credentials.Client(config);
CredentialsProvider credentialsProvider = new CredentialsProvider(){
@Override
public void setCredentials(Credentials credentials) {
}
@Override
public Credentials getCredentials() {
CredentialModel credential = credentialsClient.getCredential();
return new DefaultCredentials(credential.getAccessKeyId(), credential.getAccessKeySecret(), credential.getSecurityToken());
}
};
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint("endpoint")
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region("region")
.build();
ossClient.shutdown();
}
}
Use an AccessKey pair that automatically rotates
If your application needs long-term access to OSS, you need to manually rotate the AccessKey pair to reduce credential leak risks. In this case, you can use a client key to initialize the credential provider. The underlying logic of this method is to use an AccessKey pair to access OSS resources. After you use a client key, Key Management Service (KMS) can automatically and regularly rotate the AccessKey pair of a managed RAM user and dynamically change the static AccessKey pair of the RAM user. This reduces the risk of AccessKey pair leaks. KMS also supports immediate rotation to quickly disable a leaked AccessKey pair. This eliminates the need to manually maintain an AccessKey pair and reduces security risks and maintenance complexity. For more information about how to obtain a client key, see Create an AAP.
Add credential dependencies.
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>alibabacloud-secretsmanager-client</artifactId>
<version>1.3.7</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.7.0</version>
</dependency>
Create a configuration file named secretsmanager.properties
.
# Set the credential type to client_key.
credentials_type=client_key
# Specify the decryption password of the client key. You can read the decryption password from environment variables or a file.
client_key_password_from_env_variable=<your client key private key password environment variable name>
client_key_password_from_file_path=<your client key private key password file path>
# Specify the path of the private key file of the client key.
client_key_private_key_path=<your client key private key file path>
# Specify the ID of the region in which you want to use KMS.
cache_client_region_id=[{"regionId":"<regionId>"}]
Pass credentials by using the configuration file.
import com.aliyun.oss.common.auth.Credentials;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentials;
import com.aliyuncs.kms.secretsmanager.client.SecretCacheClient;
import com.aliyuncs.kms.secretsmanager.client.SecretCacheClientBuilder;
import com.aliyuncs.kms.secretsmanager.client.exception.CacheSecretException;
import com.aliyuncs.kms.secretsmanager.client.model.SecretInfo;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
public class ClientKeyDemoTest {
public static void main(String[] args) throws CacheSecretException {
final SecretCacheClient client = SecretCacheClientBuilder.newClient();
CredentialsProvider credentialsProvider = new CredentialsProvider() {
@Override
public void setCredentials(Credentials credentials) {
}
@Override
public Credentials getCredentials() {
try {
SecretInfo secretInfo = client.getSecretInfo("<secretName>");
JSONObject jsonObject = new JSONObject(secretInfo.getSecretValue());
String accessKeyId = jsonObject.getString("AccessKeyId");
String accessKeySecret = jsonObject.getString("AccessKeySecret");
return new DefaultCredentials(accessKeyId, accessKeySecret);
} catch (CacheSecretException | JSONException e) {
return null;
}
}
};
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint("endpoint")
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region("region")
.build();
ossClient.shutdown();
}
}
Use custom access credentials
If none of the preceding methods meet your requirements, you can specify a custom method to obtain access credentials by calling the CredentialsProvider operation. Take note that if the underlying logic is an STS token, you need to provide credential update support.
import com.aliyun.oss.common.auth.Credentials;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentials;
public class CustomCredentialProviderDemoTest {
public static void main(String[] args) {
CredentialsProvider credentialsProvider = new CredentialsProvider(){
String accessKeyId = null;
String accessKeySecrect = null;
@Override
public void setCredentials(Credentials credentials) {
}
@Override
public Credentials getCredentials() {
return new DefaultCredentials(accessKeyId, accessKeySecrect);
}
};
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint("endpoint")
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region("region")
.build();
ossClient.shutdown();
}
}
Use the default credential provider chain
If you do not specify a method to initialize a Credentials client, the default credential provider chain is used. For more information, see Default credential provider chain.
Add the credentials dependency.
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>credentials-java</artifactId>
<version>LATEST</version>
</dependency>
Use the Credentials to provide access credentials.
import com.aliyun.credentials.models.CredentialModel;
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.Credentials;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentials;
public class Demo {
public static void main(String[] args) {
com.aliyun.credentials.Client credentialsClient = new com.aliyun.credentials.Client();
CredentialsProvider credentialsProvider = new CredentialsProvider(){
@Override
public void setCredentials(Credentials credentials) {
}
@Override
public Credentials getCredentials() {
CredentialModel credential = credentialsClient.getCredential();
return new DefaultCredentials(credential.getAccessKeyId(), credential.getAccessKeySecret(), credential.getSecurityToken());
}
};
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint("endpoint")
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region("region")
.build();
ossClient.shutdown();
}
}
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](https://help-static-aliyun-doc.aliyuncs.com/assets/img/en-US/7660657371/p887525.png)
How do I view the AccessKey ID of a RAM user? Can I view the AccessKey secret of an AccessKey pair?
For information about how to view the AccessKey pair of a RAM user, see View the information about AccessKey pairs of a RAM user.
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:
Check whether the provided AccessKey pair is correct by following the instructions described in View the information about AccessKey pairs of a RAM user.
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.
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 your access to OSS over the public endpoint encounters a connection error, you may have specified an incorrect a mismatching endpoint. To fix the error, perform the following checks:
Check the region of the bucket in the OSS console.
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.
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.