Configure access credentials for OSS SDK for Java

Updated at: 2025-02-14 06:55
important

This topic contains important information on necessary precautions. We recommend that you read this topic carefully before proceeding.

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

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

  1. Configure environment variables for the AccessKey pair.

    Linux
    macOS
    Windows
    1. 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
    2. Run the following command to apply the changes:

      source ~/.bashrc
    3. Run the following commands to check whether the environment variables take effect:

      echo $OSS_ACCESS_KEY_ID
      echo $OSS_ACCESS_KEY_SECRET
    1. Run the following command in the terminal to view the default shell type:

      echo $SHELL
    2. Configure environment variables based on the default shell type.

      Zsh
      Bash
      1. 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
      2. Run the following command to apply the changes:

        source ~/.zshrc
      3. Run the following commands to check whether the environment variables take effect:

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET
      1. 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
      2. Run the following command to apply the changes:

        source ~/.bash_profile
      3. Run the following commands to check whether the environment variables take effect:

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET
    CMD
    PowerShell
    1. Run the following commands in CMD:

      setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
      setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
    2. Run the following commands to check whether the environment variables take effect:

      echo %OSS_ACCESS_KEY_ID%
      echo %OSS_ACCESS_KEY_SECRET%
    1. 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)
    2. 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)
  2. 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 {
            // 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

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.

  1. 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>
  2. 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();
            // 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");
            
            // 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 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

  1. 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>
  2. 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 {
            // 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 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 {
        // 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.NTZdStF79CVRTQuWCfXTT****"
        String accessKeySecret = "5rm8PfEiK8enp56zzAMX4RbZUraoKbWXvCf1xAuT****"
        String stsToken= "********"
        
        // 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, 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.

  1. 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>
  2. 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. 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 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.

  1. 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>
  2. 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();
            // Set the credential type to ecs_ram_role. 
            config.setType("ecs_ram_role");
            // Specify the name of the RAM role that you want to attach 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 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.

  1. 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>
  1. 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();
            // Set the credential type to oidc_role_arn.
            config.setType("oidc_role_arn");
            // Specify the ARN of the RAM role 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 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.

  1. 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>
  2. 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 {
    
            // 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 credential 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 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.

  1. 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"
      }
  2. 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>
  3. 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();
            // 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.

  1. 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>
  2. 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>"}]
  3. 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;
                    }
                }
            };
            // 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 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(){

            // 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.

  1. 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>
  2. 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();
            // 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();
        }
    }

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

How do I view the AccessKey ID of a RAM user? Can I view the AccessKey secret of an AccessKey pair?

  1. For information about how to view the AccessKey pair of a RAM user, see View the information about AccessKey pairs of a RAM user.

  2. 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:

  1. Check whether the provided AccessKey pair is correct by following the instructions described in View the information about AccessKey pairs of a RAM user.

  2. 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.

  3. 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:

  1. Check the region of the bucket in the OSS console.

  2. 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.

  3. 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.

  • On this page (1, T)
  • Usage notes
  • Credential provider initialization
  • Commonly used configuration example
  • Use the AccessKey pair of a RAM user
  • Use temporary access credentials provided by STS
  • Configuration examples for other scenarios
  • Use the ARN of a RAM role
  • Use the RAM role of an ECS instance
  • Use the RAM role of an OIDC IdP
  • Use Credentials in the context of Function Compute
  • Use credentials URIs
  • Use an AccessKey pair that automatically rotates
  • Use custom access credentials
  • Use the default credential provider chain
  • 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?
  • How do I view the AccessKey ID of a RAM user? Can I view the AccessKey secret of 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?
  • How do I fix a connection error when I access OSS by using a public OSS endpoint?
  • If an error is reported, how do I determine the type of the error?
Feedback
phone Contact Us

Chat now with Alibaba Cloud Customer Service to assist you in finding the right products and services to meet your needs.

alicare alicarealicarealicare