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.
Prerequisites
OSS SDK for Java is installed. For more information, see Installation.
Select an initialization method
Select a credential provider
OSS supports multiple methods to initialize a credential provider. You can select a suitable method based on the authentication and authorization requirements of your actual scenario.
Initialization method | Scenario | AccessKey pair or security token required | Underlying logic | 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 to access cloud services for a long period of time without frequent credential rotation. | Yes | AccessKey pair | Long-term | Manual rotation | |
Applications are deployed and run in an environment in which the AccessKey pair has high risks of leakage and require frequent rotation of the access credentials to access cloud services for a long period of time. | No | AccessKey pair | Long-term | Automatic rotation | |
Applications are deployed and run in an untrusted environment, in which case you want to manage the credential validity period and the resources that can be accessed. | Yes | Security token | Temporary | Manual refresh | |
Applications need to be authorized to access cloud services, such as cross-account access. | Yes | Security token | Temporary | Automatic refresh | |
Applications are deployed and run on Elastic Compute Service (ECS) instances, elastic container instances, and Container Service for Kubernetes (ACK) worker nodes. | No | Security token | Temporary | Automatic refresh | |
Untrusted applications are deployed and run on ACK worker nodes. | No | Security token | Temporary | Automatic refresh | |
Method 7: Use the Credentials parameter in the context of Function Compute | Functions of your applications are deployed and run in Function Compute. | No | Security token | Temporary | No need to refresh |
Applications require access credentials from external systems. | No | Security token | Temporary | Automatic refresh | |
If none of the preceding methods meet your requirements, you can specify a custom method to obtain access credentials. | Custom | Custom | Custom | Custom |
Method 1: Use an AccessKey pair
If your application is deployed in a secure and stable environment that is not vulnerable to external attacks and requires long-term access to OSS, you can use an AccessKey pair of your Alibaba Cloud account or a RAM user to initialize a credential provider. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. Take note that this method requires you to manually maintain an AccessKey pair. This poses security risks and increases maintenance complexity. For more information about how to obtain an AccessKey pair, see CreateAccessKey.
Environment variables
An Alibaba Cloud account has full access to all resources of the account. Leaks of the Alibaba Cloud account AccessKey pair pose critical threats to the system. Therefore, we recommend that you use the AccessKey pair of a RAM user that is granted the minimum necessary permissions to initialize a credential provider.
Use the AccessKey pair to specify environment variables.
Mac OS X/Linux/Unix
export OSS_ACCESS_KEY_ID=<ALIBABA_CLOUD_ACCESS_KEY_ID> export OSS_ACCESS_KEY_SECRET=<ALIBABA_CLOUD_ACCESS_KEY_SECRET>
Windows
set OSS_ACCESS_KEY_ID=<ALIBABA_CLOUD_ACCESS_KEY_ID> set OSS_ACCESS_KEY_SECRET=<ALIBABA_CLOUD_ACCESS_KEY_SECRET>
Use environment variables to pass credentials.
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 { // Obtain access credentials from environment variables. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Initialize the client by using credentialsProvider and perform subsequent operations. } }
Static credentials
You can use credentials by specifying variables in your code. In a runtime environment, the variables may be passed by actual credential values from environment variables, configuration files, or other external data sources.
The following procedure describes how to use a configuration file to pass 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>
Use the configuration file to pass credentials.
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(); // Specify the path of the configuration file. String configFilePath = "config.ini"; // Read the configuration file. FileInputStream input = new FileInputStream(configFilePath); properties.load(input); input.close(); // Obtain the AccessKey pair from the configuration file. String accessKeyId = properties.getProperty("alibaba_cloud_access_key_id"); String accessKeySecret = properties.getProperty("alibaba_cloud_access_key_secret"); CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret); // Initialize the client by using credentialsProvider and perform subsequent operations. } }
Method 2: Use an AccessKey pair that automatically rotates
If your application needs to access OSS for a long period of time, but the runtime environment faces the risk of AccessKey pair leaks, you need to manually rotate the AccessKey pair. 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 a RAM user. This reduces the risk of AccessKey pair leaks. KMS also supports immediate rotation to quickly replace 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 to the client.
<!-- 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>"}]
Use the configuration file to pass credentials.
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; } } }; // Initialize the client by using credentialsProvider and perform subsequent operations. } }
Method 3: Use a security token
If your application needs to access OSS temporarily, you can use temporary access credentials, which consist of an AccessKey pair and a security token, obtained from Security Token Service (STS) to initialize a credential provider. Take note that this method requires you to manually maintain a security token. This poses security risks and increases maintenance complexity. If you want to access OSS multiple times, you must manually refresh the security token. For more information about how to obtain a security token, see AssumeRole.
Use temporary access credentials to specify environment variables.
Mac OS X/Linux/Unix
export OSS_ACCESS_KEY_ID=<ALIBABA_CLOUD_ACCESS_KEY_ID> export OSS_ACCESS_KEY_SECRET=<ALIBABA_CLOUD_ACCESS_KEY_SECRET> export OSS_SESSION_TOKEN=<ALIBABA_CLOUD_SECURITY_TOKEN>
Windows
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>
Specify environment variables to pass temporary access credentials.
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 { // Obtain access credentials from environment variables. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Initialize the client by using credentialsProvider and perform subsequent operations. } }
Method 4: Use RAMRoleARN
If your application needs to be authorized to access OSS, for example, when you access the 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 a security token obtained from STS to configure access credentials. By specifying the Alibaba Cloud Resource Name (ARN) of a RAM role, the Credentials tool obtains the security token from STS and automatically refreshes the security token before the session expires. You can assign a value to the policy
parameter to limit the RAM role permissions. Take note that this method requires you to manually provide an AccessKey pair. This poses security risks and increases maintenance complexity. For more information about how to obtain an AccessKey pair, see CreateAccessKey. For more information about how to obtain the RAM role ARN, see CreateRole.
Add the credentials dependency.
<!-- https://mvnrepository.com/artifact/com.aliyun/credentials-java --> <dependency> <groupId>com.aliyun</groupId> <artifactId>credentials-java</artifactId> <version>0.3.4</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(); // 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 by specifying 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 by specifying 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()); } }; // Initialize the client by using credentialsProvider and perform subsequent operations. } }
Method 5: Use ECSRAMRole
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 a security 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 security token on the instance. This method eliminates the risks that may arise when you manually maintain an AccessKey pair or a security token. For more information about how to obtain the ECSRAMRole role, see CreateRole. For more information about how to assign ECSRAMRoles to ECS instances, see Grant ECS access to other Alibaba Cloud services by using 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>0.3.4</version> </dependency>
Configure ECSRAMRole 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 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. This parameter is optional. If you do not configure this parameter, the system automatically searches for a RAM role. We recommend that you configure this parameter to reduce the number of requests. 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()); } }; // Initialize the client by using credentialsProvider and perform subsequent operations. } }
Method 6: Use OIDCRoleARN
After the RAM role is configured on the ACK worker node, the application in a pod on the node can obtain the security 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 a security 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 security 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 a security 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 of environment variables and calls the AssumeRoleWithOIDC operation of STS to obtain the security token of attached roles. This method eliminates the risks that may arise when you manually maintain an AccessKey pair or a security token. 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>0.3.4</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 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 by specifying the ALIBABA_CLOUD_ROLE_ARN environment variable. config.setRoleArn("<RoleArn>"); // Specify the ARN of the OIDC IdP by specifying the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable. config.setOidcProviderArn("<OidcProviderArn>"); // Specify the path of the OIDC token file by specifying the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable. config.setOidcTokenFilePath("<OidcTokenFilePath>"); // Specify the role session name by specifying 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()); } }; // Initialize the client by using credentialsProvider and perform subsequent operations. } }
Method 7: Use the Credentials parameter 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 the Credentials parameter in the context of Function Compute. The underlying logic of this method is to use a security token obtained from STS to configure access credentials. Function Compute obtains a security token by assuming a service role based on the role configured for the function. Then, the security token is passed to your application by using the Credentials parameter in the context of Function Compute. The security token is valid for 36 hours. You cannot change its validity period. The maximum execution time of a function is 24 hours. Therefore, you do not need to refresh the security token because it does not expire when the function is executed. This method eliminates the risks that may arise when you manually maintain an AccessKey pair or a security token. 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 dependencies.
<!-- 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 the Credentials parameter 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 { // 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 the role must have the required OSS permissions. We recommend that you use the AliyunFCDefaultRole role. Credentials creds = context.getExecutionCredentials(); // Use the obtained credential to create a credential provider instance. CredentialsProvider credentialsProvider = new DefaultCredentialProvider(creds.getAccessKeyId(), creds.getAccessKeySecret(), creds.getSecurityToken()); // Initialize the client by using credentialsProvider and perform subsequent operations. outputStream.write(new String("done").getBytes()); } }
Method 8: Use CredentialsURI
If your application needs to obtain an Alibaba Cloud credential 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 a security token obtained from STS to configure access credentials. The Credentials tool obtains the security token by using the URI that you specify to initialize the credential client. This method eliminates the risks that may arise when you manually maintain an AccessKey pair or a security token. Take note that the backend service that provides the CredentialsURI response must automatically refresh the security token to ensure that your application can always obtain a valid credential.
To allow the Credentials tool to correctly parse and use a security token, the URI must comply with the following response protocol:
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>0.3.4</version> </dependency>
Configure the CredentialsURI 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(); // Set the credential type to credentials_uri. config.setType("credentials_uri"); // Specify the URI of the credential in the http://local_or_remote_uri/ format by specifying 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()); } }; // Initialize the client by using credentialsProvider and perform subsequent operations. } }
Method 9: 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 Credential Providers operation. Take note that if the underlying logic is a security 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(){
// Initialize variable.
String accessKeyId = null;
// Initialize variable.
String accessKeySecrect = null;
// Initialize 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 consists 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 a security token.
// Refresh the temporary access credentials based on the expiration time.
// return new DefaultCredentials(accessKeyId, accessKeySecrect, token);
}
};
// Initialize the client by using credentialsProvider and perform subsequent operations.
}
}
What to do next
After initializing the credential provider, you need to use the credential provider to create an OSSClient instance. For more information, see Initialization.