All Products
Search
Document Center

Object Storage Service:How to configure access credentials for OSS SDK for Java

Last Updated:Jul 25, 2024

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.

Initialize a credential provider

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 STS token required

Underlying credential

Credential validity period

Credential rotation or refresh method

Method 1: Use an AccessKey pair

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

AK

Long-term

Manual rotation

Method 2: Use an AccessKey pair that automatically rotates

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.

No

AK

Long-term

Automatic rotation

Method 3: Use an STS token

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

Method 4: Use RAMROLEARN

Applications need to be authorized to access cloud services, such as cross-account access.

Yes

STS Token

Temporary

Automatic refresh

Method 5: Use ECSRAMRole

Applications are deployed and run on Elastic Compute Service (ECS) instances, elastic container instances, and Container Service for Kubernetes (ACK) worker nodes.

No

STS Token

Temporary

Automatic refresh

Method 6: Use OIDCRoleARN

Untrusted applications are deployed and run on ACK worker nodes.

No

STS Token

Temporary

Automatic refresh

Method 7: Use the Credentials parameter in the context of Function Compute

Applications are deployed and run in a function of Function Compute.

No

STS Token

Temporary

No need to refresh

Method 8: Use CredentialsURI

Applications require access credentials from external systems.

No

STS Token

Temporary

Automatic refresh

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.

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

Warning

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.

  1. 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>
  2. 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();
            // Use credentialsProvider for 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.

  1. Create a configuration file named config.ini.

    [credentials]
    accessKeyId = <ALIBABA_CLOUD_ACCESS_KEY_ID>
    accessKeySecret = <ALIBABA_CLOUD_ACCESS_KEY_SECRET>
  2. 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("accessKeyId");
            String accessKeySecret = properties.getProperty("accessKeySecret");
    
            CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);
    
            // Use credentialsProvider for 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.

  1. 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>
  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. 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;
                    }
                }
            };
            // Use credentialsProvider for subsequent operations.
        }
    }
    

Method 3: Use an STS 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.

Environment variables

  1. 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>
  2. 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();
            
            // Use credentialsProvider for 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.

  1. Create a configuration file named config.ini.

    [credentials]
    accessKeyId = <ALIBABA_CLOUD_ACCESS_KEY_ID>
    accessKeySecret = <ALIBABA_CLOUD_ACCESS_KEY_SECRET>
    securityToken = <ALIBABA_CLOUD_SECURITY_TOKEN>
  2. 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 and the security token from the configuration file.
            String accessKeyId = properties.getProperty("accessKeyId");
            String accessKeySecret = properties.getProperty("accessKeySecret");
            String securityToken = properties.getProperty("securityToken");
    
            CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);
            // Use credentialsProvider for 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 and a security token. This poses security risks and increases maintenance complexity. For more information about how to obtain an AccessKey pair or an STS token, see CreateAccessKey or AssumeRole. For more information about how to obtain the RAM role ARN, see CreateRole.

AccessKey pair and RAMROLEARN

  1. 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>
  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");
            // Obtain the RamRoleArn of the RAM role from the environment variable.
            config.setRoleArn(System.getenv().get("ALIBABACLOUD_STS_ROLE_ARN"));
            // Obtain the AccessKey ID from the environment variable.
            config.setAccessKeyId(System.getenv().get("ALIBABACLOUD_ACCESS_KEY_ID"));
            // Obtain the AccessKey secret from the environment variable.
            config.setAccessKeySecret(System.getenv().get("ALIBABACLOUD_ACCESS_KEY_SECRET"));
            // Specify the session name of the RAM role.
            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 for subsequent operations.
        }
    }

Security Token and RAMoleARN

  1. 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>
  2. Configure the security token and RAMROLEARN as the 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 RamRoleArnStsDemoTest {
    
        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");
            // Obtain the RamRoleArn of the RAM role from the environment variable.
            config.setRoleArn(System.getenv().get("ALIBABACLOUD_STS_ROLE_ARN"));
            // Obtain temporary access credentials from environment variables.
            config.setAccessKeyId(System.getenv().get("ALIBABACLOUD_ACCESS_KEY_ID"));
            config.setAccessKeySecret(System.getenv().get("ALIBABACLOUD_ACCESS_KEY_SECRET"));
            config.setAccessKeySecret(System.getenv().get("ALIBABA_CLOUD_SECURITY_TOKEN"));
            // Specify the session name of the RAM role.
            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 for 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.

  1. 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>
  2. 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("ECSRAMRole");
            // Enable the security hardening mode of the metadata of the ECS instance. This parameter is optional. We recommend that you configure this parameter to improve the overall security of the system. 
            config.setEnableIMDSv2(true);
    
            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 for subsequent operations.
        }
    }

Method 6: Use OIDCRoleARN

After the RAM role is configured on the ACK worker node, the application in a pod on the corresponding 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.

  1. 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>
  1. 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");
            // Obtain the temporary AccessKey ID from the environment variable.
            config.setAccessKeyId(System.getenv().get("ALIBABACLOUD_ACCESS_KEY_ID"));
            // Obtain temporary AccessKey secret from the environment variable.
            config.setAccessKeySecret(System.getenv().get("ALIBABACLOUD_ACCESS_KEY_SECRET"));
            // Obtain the temporary security token from the environment variable.
            config.setSecurityToken(System.getenv().get("ALIBABA_CLOUD_SECURITY_TOKEN"));
            // Specify the ARN of the RAM role, which is the ID of the RAM role to be assumed.
            config.setRoleArn(System.getenv("ALIBABA_CLOUD_ROLE_ARN"));
            // Specify the ARN of the OIDC IdP.
            config.setOidcProviderArn(System.getenv("ALIBABA_CLOUD_OIDC_PROVIDER_ARN"));
            // Specify the path of the file in which the OIDC token is stored.
            config.setOidcTokenFilePath(System.getenv("ALIBABA_CLOUD_OIDC_TOKEN_FILE"));
            // Specify the name of the role session.
            config.setRoleSessionName("<RoleSessionName>");
            // Optional. Specify limited permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}.
            config.setPolicy("<Policy>");
            // Optional. Specify the external ID of the RAM role. 
            // The external ID is provided by the credentials provider to avoid proxy confusion. 
            config.setExternalId("<ExternalId>");
            // 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 for 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. A function can execute up to 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.

  1. 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>
  2. 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());
    
            // Use credentialsProvider for 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.

  1. 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"
      }
  2. 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>
  3. 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 to obtain a credential in the http://local_or_remote_uri/ format.
            config.setCredentialsUri("<local_or_remote_uri>");
    
            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 for 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);
            }
        };
        // Use credentialsProvider for 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.