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.
Usage notes
For a list of OSS regions and endpoints, see Regions and endpoints.
For information about how to create an AccessKey pair for a RAM user, see Create an AccessKey pair for a RAM user.
To support the V4 signature algorithm, use OSS SDK for Java V3.17.4 or later. For more information, see Install OSS SDK for Java.
Credential provider initialization
OSS supports multiple methods for initializing 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 |
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 | AccessKey pair | Long-term | Manual rotation | |
Applications are deployed and run in an untrusted environment, and you want to manage the credential validity and the resources that can be accessed. | Yes | Security Token Service (STS) token | Temporary | Manual refresh | |
Applications require access to cloud services, such as cross-account access. | Yes | STS token | Temporary | Automatic refresh | |
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 | |
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 |
Applications require access credentials from external systems. | No | STS token | Temporary | Automatic refresh | |
Applications are deployed in an environment where AccessKey pairs are at high risk of leakage, and require frequent rotation of access credentials to gain long-term access to cloud services. | No | AccessKey pair | Long-term | Automatic rotation | |
If none of the preceding methods meet your requirements, you can use a custom method to obtain access credentials. | Custom | Custom | Custom | Custom | |
If you do not specify a method to initialize a Credentials client, the default credential provider chain is used. | No | Custom | Custom | Automatic refresh |
Configuration examples for common scenarios
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.
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 of the RAM user.
Linux
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:
source ~/.bashrc
Run the following commands to 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
~/.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:
source ~/.zshrc
Run the following commands to check whether the environment variables take 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_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:
source ~/.bash_profile
Run the following commands to check whether the environment variables take 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"
Run the following commands to 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)
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)
To make sure that your settings are loaded, restart or refresh your compilation and runtime environments, such as the IDE, command-line tool, desktop applications, and services in the background.
Pass credentials by using environment variables.
import com.aliyun.oss.ClientBuilderConfiguration; import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.common.auth.CredentialsProviderFactory; import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider; import com.aliyun.oss.common.comm.SignVersion; public class AkDemoTest { public static void main(String[] args) throws Exception { // Obtain access credentials from environment variables. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Use credentialsProvider for subsequent operations. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); // Create an OSSClient instance. OSS ossClient = OSSClientBuilder.create() .endpoint("endpoint") .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region("region") .build(); ossClient.shutdown(); } }
Static credentials
Below is the sample code for hardcoding the access credentials to explicitly specify the AccessKey pair that you want to use to access OSS.
Do not embed access credentials in application code deployed in a production environment. This method is intended only for testing.
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.SignVersion;
public class AkDemoTest {
public static void main(String[] args) throws Exception {
// Specify the AccessKey ID and AccessKey secret of the RAM user.
String accessKeyId = "yourAccessKeyID";
String accessKeySecret = "yourAccessKeySecret";
// Pass the AccessKey ID and secret to DefaultCredentialProvider to initialize the credential provider.
CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);
// Use credentialsProvider to initialize the client.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
// Explicitly declare the use of the V4 signature algorithm.
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
// Create an OSSClient instance.
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 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 prolong access after the existing STS token expires, you must manually refresh the STS token.
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
WarningNote that the temporary access credentials (AccessKey ID, AccessKey secret, and STS token) provided by STS are used instead of the AccessKey ID and AccessKey secret of the RAM user.
The AccessKey ID provided by STS starts with STS. 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
WarningNote 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.****************.
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 credential information by using environment variables.
import com.aliyun.oss.ClientBuilderConfiguration; import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.common.auth.CredentialsProviderFactory; import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider; import com.aliyun.oss.common.comm.SignVersion; public class StsDemoTest { public static void main(String[] args) throws Exception { // Obtain access credentials from environment variables. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Use credentialsProvider to initialize the client. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); // Explicitly declare the use of the V4 signature algorithm. clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); // Create an OSSClient instance. OSS ossClient = OSSClientBuilder.create() .endpoint("endpoint") .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region("region") .build(); ossClient.shutdown(); } }
Static credentials
You can hardcode the credentials in your application to explicitly specify the AccessKey pair that you want to use to access OSS.
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.SignVersion;
public class StsDemoTest {
public static void main(String[] args) throws Exception {
// Specify the AccessKey ID, AccessKey secret, and STS token that are provided by STS, rather than the AccessKey ID and AccessKey secret of the RAM user.
// The AccessKey ID provided by STS starts with STS.
String accessKeyId = "STS.****************";
String accessKeySecret = "yourAccessKeySecret";
String stsToken= "yourSecurityToken";
// Pass the AccessKey ID and secret to DefaultCredentialProvider to initialize the credential provider.
CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret, stsToken);
// Use credentialsProvider to initialize the client.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
// Explicitly declare the use of the V4 signature algorithm.
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
// Create an OSSClient instance.
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, in a cross-account access scenario, you can use the Alibaba Cloud Resource Name (ARN) of a RAM role 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 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.
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. The ARN of the RAM role is included in the response. For more information, see CreateRole.
Add the credentials dependency.
<!-- https://mvnrepository.com/artifact/com.aliyun/credentials-java --> <dependency> <groupId>com.aliyun</groupId> <artifactId>credentials-java</artifactId> <version>LATEST</version> </dependency>
Use an AccessKey pair and the ARN of a RAM role as access credentials.
import com.aliyun.credentials.models.CredentialModel; import com.aliyun.oss.ClientBuilderConfiguration; import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.common.auth.Credentials; import com.aliyun.oss.common.auth.CredentialsProvider; import com.aliyun.oss.common.auth.DefaultCredentials; import com.aliyun.oss.common.comm.SignVersion; public class RamRoleArnAkDemoTest { public static void main(String[] args) { com.aliyun.credentials.models.Config config = new com.aliyun.credentials.models.Config(); // Set the credential type to ram_role_arn. config.setType("ram_role_arn"); // Specify the ARN of the RAM role that you want your application to assume. You can specify the ARN of the RAM role by using the ALIBABA_CLOUD_ROLE_ARN environment variable. Example: acs:ram::123456789012****:role/adminrole. config.setRoleArn("<RoleArn>"); // Obtain the AccessKey ID from the environment variable. config.setAccessKeyId(System.getenv().get("ALIBABA_CLOUD_ACCESS_KEY_ID")); // Obtain the AccessKey secret from the environment variable. config.setAccessKeySecret(System.getenv().get("ALIBABA_CLOUD_ACCESS_KEY_SECRET")); // Specify the role session name. You can obtain the value from the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable. config.setRoleName("<RoleSessionName>"); // (Optional) Specify limited permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"} config.setPolicy("<Policy>"); // (Optional) Specify the validity period of the role session. 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()); } }; // Use credentialsProvider to initialize the client. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); // Explicitly declare the use of the V4 signature algorithm. clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); // Create an OSSClient instance. 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 the RAM role of the ECS instance to initialize a credential provider. The underlying logic of this method is to use an STS token obtained from STS to configure access credentials. You can 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.
<!-- https://mvnrepository.com/artifact/com.aliyun/credentials-java --> <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.ClientBuilderConfiguration; import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.common.auth.Credentials; import com.aliyun.oss.common.auth.CredentialsProvider; import com.aliyun.oss.common.auth.DefaultCredentials; import com.aliyun.oss.common.comm.SignVersion; public class EcsRamRoleDemoTest { public static void main(String[] args) { com.aliyun.credentials.models.Config config = new com.aliyun.credentials.models.Config(); // Set the credential type to ecs_ram_role. config.setType("ecs_ram_role"); // Specify the name of the RAM role that is attached to the ECS instance. 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()); } }; // Use credentialsProvider to initialize the client. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); // Explicitly declare the use of the V4 signature algorithm. clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); // Create an OSSClient instance. OSS ossClient = OSSClientBuilder.create() .endpoint("endpoint") .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region("region") .build(); ossClient.shutdown(); } }
Use the role of an OIDC IdP
After the RAM role is configured on the ACK worker node, applications within pods on that node can retrieve the STS token for the attached role by using the metadata server, similar to an application deployed on an ECS instance. However, you might not want untrusted applications, such as those submitted by customers without disclosing the application code to you, to access the metadata server for obtaining the 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 for 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.
<!-- https://mvnrepository.com/artifact/com.aliyun/credentials-java --> <dependency> <groupId>com.aliyun</groupId> <artifactId>credentials-java</artifactId> <version>LATEST</version> </dependency>
Use the role of an OIDC IdP to provide access credentials.
import com.aliyun.credentials.models.CredentialModel; import com.aliyun.oss.ClientBuilderConfiguration; import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.common.auth.Credentials; import com.aliyun.oss.common.auth.CredentialsProvider; import com.aliyun.oss.common.auth.DefaultCredentials; import com.aliyun.oss.common.comm.SignVersion; public class OidcRoleArnDemoTest { public static void main(String[] args) { com.aliyun.credentials.models.Config config = new com.aliyun.credentials.models.Config(); // Set the credential type to oidc_role_arn. config.setType("oidc_role_arn"); // Specify the ARN of the RAM role. You can do so by using the ALIBABA_CLOUD_ROLE_ARN environment variable. config.setRoleArn("<RoleArn>"); // Specify the ARN of the OIDC IdP. You can obtain the value from the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable. config.setOidcProviderArn("<OidcProviderArn>"); // Specify the path of the OIDC token file. You can obtain the value from the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable. config.setOidcTokenFilePath("<OidcTokenFilePath>"); // Specify the role session name. You can obtain the value from the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable. config.setRoleSessionName("<RoleSessionName>"); // (Optional) Specify limited permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"} config.setPolicy("<Policy>"); // Specify the validity period of the session. 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()); } }; // Use credentialsProvider to initialize the client. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); // Explicitly declare the use of the V4 signature algorithm. clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); // Create an OSSClient instance. 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 for 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.
<!-- https://mvnrepository.com/artifact/com.aliyun.fc.runtime/fc-java-core --> <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.
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.ClientBuilderConfiguration; import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.common.comm.SignVersion; public class App implements StreamRequestHandler { @Override public void handleRequest( InputStream inputStream, OutputStream outputStream, Context context) throws IOException { // Obtain the key information. Before you execute the function, make sure that the role of the service to which the function belongs is configured and that the role has required permissions to access OSS. We recommend that you use the AliyunFCDefaultRole role. Credentials creds = context.getExecutionCredentials(); // Use the obtained credentials to create a credential provider instance. CredentialsProvider credentialsProvider = new DefaultCredentialProvider(creds.getAccessKeyId(), creds.getAccessKeySecret(), creds.getSecurityToken()); // Use credentialsProvider to initialize the client. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); // Explicitly declare the use of the V4 signature algorithm. clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); // Create an OSSClient instance. 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 specified URI to initialize the client. This method does not require an AccessKey pair or STS token, eliminating the risks associated with manually managing these credentials.
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:
Response status code: 200
Response body structure:
{ "Code": "Success", "AccessKeySecret": "AccessKeySecret", "AccessKeyId": "AccessKeyId", "Expiration": "2021-09-26T03:46:38Z", "SecurityToken": "SecurityToken" }
Add the credentials dependency.
<!-- https://mvnrepository.com/artifact/com.aliyun/credentials-java --> <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.ClientBuilderConfiguration; import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.common.auth.Credentials; import com.aliyun.oss.common.auth.CredentialsProvider; import com.aliyun.oss.common.auth.DefaultCredentials; import com.aliyun.oss.common.comm.SignVersion; public class CredentialsUriDemoTest { public static void main(String[] args) { com.aliyun.credentials.models.Config config = new com.aliyun.credentials.models.Config(); // Set the credential type to credentials_uri. config.setType("credentials_uri"); // Specify the credentials URI. The URI is the address of the server that generates an STS token in the http://local_or_remote_uri/ format. You can specify the URI by using the ALIBABA_CLOUD_CREDENTIALS_URI environment variable. 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()); } }; // Use credentialsProvider to initialize the client. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); // Explicitly declare the use of the V4 signature algorithm. clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); // Create an OSSClient instance. 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.
<!-- https://mvnrepository.com/artifact/com.aliyun/alibabacloud-secretsmanager-client --> <dependency> <groupId>com.aliyun</groupId> <artifactId>alibabacloud-secretsmanager-client</artifactId> <version>1.3.7</version> </dependency> <!-- https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-core --> <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.ClientBuilderConfiguration; import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.common.auth.Credentials; import com.aliyun.oss.common.auth.CredentialsProvider; import com.aliyun.oss.common.auth.DefaultCredentials; import com.aliyun.oss.common.comm.SignVersion; 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; } } }; // Use credentialsProvider to initialize the client. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); // Explicitly declare the use of the V4 signature algorithm. clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); // Create an OSSClient instance. 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 implementation is based on an STS token, you need to provide credential update support.
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.Credentials;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentials;
import com.aliyun.oss.common.comm.SignVersion;
public class CustomCredentialProviderDemoTest {
public static void main(String[] args) {
CredentialsProvider credentialsProvider = new CredentialsProvider(){
// Initialize the variable.
String accessKeyId = null;
// Initialize the variable.
String accessKeySecrect = null;
// Initialize the variable.
// String token = null;
@Override
public void setCredentials(Credentials credentials) {
}
@Override
public Credentials getCredentials() {
//TODO
// Specify a custom method to obtain access credentials.
// Return long-term access credentials, which consist of an AccessKey ID and an AccessKey secret.
return new DefaultCredentials(accessKeyId, accessKeySecrect);
// Return temporary access credentials, which consists of an AccessKey ID, an AccessKey secret, and an STS token.
// Refresh the temporary access credentials based on the expiration time.
// return new DefaultCredentials(accessKeyId, accessKeySecrect, token);
}
};
// Use credentialsProvider to initialize the client.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
// Explicitly declare the use of the V4 signature algorithm.
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
// Create an OSSClient instance.
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.
<!-- https://mvnrepository.com/artifact/com.aliyun/credentials-java --> <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; import com.aliyun.oss.common.comm.SignVersion; 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(); // Explicitly declare the use of the V4 signature algorithm. clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); // Use credentialsProvider to initialize the client. // Create an OSSClient instance. OSS ossClient = OSSClientBuilder.create() .endpoint("endpoint") .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region("region") .build(); ossClient.shutdown(); } }