Skip to content

Latest commit

 

History

History
626 lines (497 loc) · 32.2 KB

1-Credentials.md

File metadata and controls

626 lines (497 loc) · 32.2 KB

← Overview | Credentials(中文) | Endpoint →


Credentials

To prevent credential leakage, do not hardcode credentials in plaintext in your code. Volcengine provides multiple secure ways to load credentials, such as environment variables.

Environment Variable Setup

Linux

⚠️ Note

Environment variables configured with export are only effective for the current session. They will be lost when the session ends. To persist them, add the exports to your shell startup scripts.

Key Command
VOLCENGINE_ACCESS_KEY export VOLCENGINE_ACCESS_KEY=yourAccessKeyID
VOLCENGINE_SECRET_KEY export VOLCENGINE_SECRET_KEY=yourSecretAccessKey
VOLCENGINE_SESSION_TOKEN export VOLCENGINE_SESSION_TOKEN=yourSessionToken

Verify: run echo $VOLCENGINE_ACCESS_KEY. If it returns the correct value, the configuration is effective.

Windows

Two options are provided: GUI setup and command line setup.

Verify: open Command Prompt and run echo %VOLCENGINE_ACCESS_KEY%, echo %VOLCENGINE_SECRET_KEY%, echo %VOLCENGINE_SESSION_TOKEN%. If the returned values are correct, the configuration is effective.

GUI Setup

On Windows 10, right-click This PC → Properties → Advanced system settings → Environment Variables → System variables / User variables → New, then set:

Variable Example
AccessKey Id Name: VOLCENGINE_ACCESS_KEY
Value: *****
AccessKey Secret Name: VOLCENGINE_SECRET_KEY
Value: *****
Session Token Name: VOLCENGINE_SESSION_TOKEN
Value: *****
Command Line Setup

Run Command Prompt as Administrator, and add environment variables:

setx VOLCENGINE_ACCESS_KEY yourAccessKeyID /M
setx VOLCENGINE_SECRET_KEY yourAccessKeySecret /M
setx VOLCENGINE_SESSION_TOKEN yourSessionToken /M

⚠️ Note

/M means system-level variables. You may omit it for user-level variables.

Credential Providers Overview

Provider Purpose Auto Refresh Typical Scenario
StaticCredentialProvider Static AK/SK(/Token) No Long-lived server credentials
StsAssumeRoleProvider STS AssumeRole Yes IAM role-based temporary credentials
OidcCredentialProvider STS AssumeRoleWithOIDC Yes OIDC federation
SamlCredentialProvider STS AssumeRoleWithSAML Yes SAML federation
EnvironmentVariableCredentialProvider Read AK/SK(/Token) from env No CI/CD and container env injection
CLIConfigCredentialProvider Read from $HOME/.volcengine/config.json Depends on mode Reuse CLI profile and login state
CLIOrDefaultCredentialProvider CLI profile selected like the ve CLI, else the default chain Depends on selection Tools that pick credentials like ve
EcsRoleCredentialProvider Read from ECS IMDS Yes ECS instance role credentials
DefaultCredentialProvider Default chain wrapper Depends on delegated provider No AK/SK in application code

Supported VOLCENGINE Environment Variables

  • Basic credentials:
    • VOLCENGINE_ACCESS_KEY
    • VOLCENGINE_SECRET_KEY
    • VOLCENGINE_SESSION_TOKEN
  • OIDC:
    • VOLCENGINE_OIDC_ROLE_TRN
    • VOLCENGINE_OIDC_TOKEN_FILE
    • VOLCENGINE_OIDC_ROLE_SESSION_NAME
    • VOLCENGINE_OIDC_ROLE_POLICY
    • VOLCENGINE_OIDC_STS_ENDPOINT
  • CLI config:
    • VOLCENGINE_CLI_CONFIG_FILE
    • VOLCENGINE_PROFILE
    • VOLCSTACK_PROFILE (fallback of VOLCENGINE_PROFILE, used by CLIOrDefaultCredentialProvider)
    • VOLCENGINE_DISABLE_DEFAULT_CREDENTIALS (CLIOrDefaultCredentialProvider only)
  • ECS metadata:
    • VOLCENGINE_ECS_METADATA
    • VOLCENGINE_ECS_METADATA_DISABLED

For full details, see Environment Variables.

AK/SK

AK/SK is a pair of permanent access keys created in the Volcengine console. The SDK signs each request to authenticate.

⚠️ Notes

  1. Do not embed or expose AK/SK in client-side applications.
  2. Use a configuration center or environment variables.
  3. Follow least privilege principles.
import com.volcengine.ApiClient;
import com.volcengine.sign.Credentials;

public class SampleCode {
    public static void main(String[] args) {
        String ak = "Your AK";
        String sk = "Your SK";
        String region = "cn-beijing";

        // 1. Using static AK/SK may leak credentials; do not use in production.
        Credentials akSkCredential = Credentials.getCredentials(ak, sk);
        // 2. Recommended in production: read from env vars: VOLCENGINE_ACCESS_KEY / VOLCENGINE_SECRET_KEY
        // Credentials akSkCredential = Credentials.getEnvCredentials();

        ApiClient apiClient = new ApiClient()
            .setCredentials(akSkCredential)
            .setRegion(region);
    }
}

STS Token

STS (Security Token Service) provides temporary credentials (temporary AK/SK and Token).

⚠️ Notes

  1. Least privilege.
  2. Use a reasonable TTL. Shorter is safer; avoid exceeding 1 hour.
import com.volcengine.ApiClient;
import com.volcengine.sign.Credentials;

public class SampleCode {
    public static void main(String[] args) {
        String ak = "Your AK";
        String sk = "Your SK";
        String sessionToken = "Your Session Token";
        String region = "cn-beijing";

        Credentials sessionTokenCredential = Credentials.getCredentials(ak, sk, sessionToken);
        // Credentials sessionTokenCredential = Credentials.getEnvCredentials();

        ApiClient apiClient = new ApiClient()
            .setCredentials(sessionTokenCredential)
            .setRegion(region);
    }
}

StaticCredentialProvider

To wrap static AK/SK(/Token) in the Provider form (so the API style matches the dynamic providers), use StaticCredentialProvider:

import com.volcengine.ApiClient;
import com.volcengine.auth.CredentialProvider;
import com.volcengine.auth.StaticCredentialProvider;

public class SampleCode {
    public static void main(String[] args) {
        // sessionToken may be null (long-lived AK/SK scenario)
        StaticCredentialProvider staticProvider = new StaticCredentialProvider(
            "Your AK",
            "Your SK",
            "Your Session Token");

        CredentialProvider credentialProvider = new CredentialProvider(staticProvider);

        ApiClient apiClient = new ApiClient()
            .setCredentialProvider(credentialProvider)
            .setRegion("cn-beijing");
    }
}

STS Provider Configuration and Migration

The following proxy/TLS rules apply to StsAssumeRoleProvider, OidcCredentialProvider, and SamlCredentialProvider:

  • proxyUrl supports only HTTP forward proxies: http://[user:password@]host:port, with an explicit port in 1..65535. HTTPS STS can use CONNECT through an HTTP proxy; TLS-to-proxy (https:// proxy URLs) and SOCKS are unsupported.
  • An explicit provider proxy takes precedence over the bound client's explicit httpProxy / httpsProxy, selected by the STS URL scheme, not the business API scheme. Without either, OIDC/SAML use the JVM default ProxySelector, including JVM http.proxyHost / http.proxyPort and https.proxyHost / https.proxyPort system properties. They do not parse HTTP_PROXY / HTTPS_PROXY or their lowercase variants. AssumeRole retains its original ApiClient proxy selection, including supported proxy environment variables.
  • OIDC/SAML form POSTs use OkHttp with connection retries disabled. maxRetries=0 sends one attempt if the server closes after receiving the form without responding; n permits at most n+1 SDK attempts. Where JVM redirects are enabled, a same-scheme 307 preserves the POST and its form. Basic authentication challenges and redirects are bounded HTTP follow-ups within an attempt. Terminal 401/403/407 bodies remain readable. HTTPS without an explicit proxy uses the JVM-enabled TLS protocols and cipher suites, the default SSL socket factory unless the provider overrides it, and standard hostname matching before the caller verifier fallback.
  • An empty caFile together with insecureSkipVerify=false removes the provider TLS override and uses the original transport TLS settings, which may include a custom factory. JVM default trust applies only when the original settings were not customized. insecureSkipVerify=true takes precedence over caFile; clearing the CA alone does not restore verification.

Snapshot migration: When supplied directly through CredentialProvider, these exact built-in classes are snapshotted on first credential access by each ApiClient, with separate caches and refresh locks. Changing the source object's role, source credentials, proxy, TLS, expiry, or retry settings no longer updates an existing binding. After changes, call apiClient.setCredentialProvider(credentialProvider) again on each affected client; use a new provider for constructor-only settings. Setting the source AssumeRole provider's expiration time to 0 does not force an existing binding to refresh. Separate client caches may increase STS calls. Custom providers, subclasses, and the default credential chain retain their existing behavior.

For AssumeRole's internal ApiClient, the snapshot isolates the SDK retry count, backoff delay bounds, and retryErrorCodes set while retaining custom strategies' runtime types. Strategies with additional mutable references must override BackoffStrategy.copy() / RetryCondition.copy(), call super.copy(), and copy those fields on the result. This is not a deep-copy guarantee for arbitrary objects such as JSON helpers, interceptors, or TLS factories. OIDC/SAML snapshot their retry count and interval; OIDC still reads the token file at refresh time. See Proxy for binding and transport details.

AssumeRole

AssumeRole supports dynamic credentials with auto refresh.

⚠️ Notes

  1. Least privilege.
  2. Choose a reasonable TTL; maximum is 12 hours.
  3. Use fine-grained roles and policies.
import com.volcengine.auth.CredentialProvider;
import com.volcengine.auth.StsAssumeRoleProvider;

public class SampleCode {
    public static void main(String[] args) {
        String region = "cn-beijing";
        StsAssumeRoleProvider stsAssumeRoleProvider = new StsAssumeRoleProvider(
            "YourAccessKey",
            "YourSecretKey",
            "YourRoleName",
            "YourAccountId");

        // Optional fields
        stsAssumeRoleProvider.setHost("sts.volcengineapi.com");
        stsAssumeRoleProvider.setRegion("cn-beijing");
        stsAssumeRoleProvider.setDurationSeconds(3600);
        stsAssumeRoleProvider.setExpireBufferSeconds(60);
        stsAssumeRoleProvider.setSchema("https");
        // Proxy / TLS for reaching STS (optional)
        // stsAssumeRoleProvider.setProxyUrl("http://user:pass@10.0.0.1:8080"); // HTTP forward proxy; explicit port 1..65535; fallback rules above
        // stsAssumeRoleProvider.setCaFile("/path/to/ca.pem");                  // PEM CA; empty + insecureSkipVerify=false restores original transport TLS, possibly custom
        // stsAssumeRoleProvider.setInsecureSkipVerify(false);                  // Pass true to skip STS TLS verification (self-signed / intercepting proxy); debugging only, default false, never in production
        CredentialProvider credentialProvider = new CredentialProvider(stsAssumeRoleProvider);

        ApiClient apiClient = new ApiClient()
            .setCredentialProvider(credentialProvider)
            .setRegion(region);
    }
}

OIDC (AssumeRoleWithOIDC)

OidcCredentialProvider gets temporary credentials from STS via OIDC token.

Reference: https://www.volcengine.com/docs/6257/1494877

Explicit Parameter Example

import com.volcengine.ApiClient;
import com.volcengine.auth.CredentialProvider;
import com.volcengine.auth.OidcCredentialProvider;

public class SampleCode {
    public static void main(String[] args) {
        String region = "cn-beijing";

        OidcCredentialProvider oidcProvider = new OidcCredentialProvider(
            "trn:iam::1234567890:role/oidc-role", // roleTrn
            null,                                 // roleSessionName (optional)
            "/var/run/secrets/oidc/token",        // oidcTokenFile
            null,                                 // rolePolicy (optional)
            "sts.volcengineapi.com"               // stsEndpoint (optional)
        );
        // Optional setters
        oidcProvider.setDurationSeconds(3600);          // Credential TTL in seconds, default: 3600
        oidcProvider.setExpireBufferSeconds(60);         // Expire buffer in seconds, default: 300
        oidcProvider.setSchema("https");                // STS scheme, default: https
        oidcProvider.setMaxRetries(3);                  // Retry attempts, default: 3, 0 disables retry
        oidcProvider.setRetryIntervalMs(1000);          // Retry interval in ms, default: 1000
        // Proxy / TLS for reaching STS (optional)
        // oidcProvider.setProxyUrl("http://user:pass@10.0.0.1:8080"); // HTTP forward proxy; empty uses client STS-scheme fallback, then JVM ProxySelector, not proxy env vars
        // oidcProvider.setCaFile("/path/to/ca.pem");                  // PEM CA; empty + insecureSkipVerify=false uses original transport TLS, possibly custom
        // oidcProvider.setInsecureSkipVerify(false);                  // Pass true to skip STS TLS verification; debugging only, default false, never in production

        CredentialProvider credentialProvider = new CredentialProvider(oidcProvider);
        ApiClient apiClient = new ApiClient()
            .setCredentialProvider(credentialProvider)
            .setRegion(region);
    }
}

Environment-variable Example

import com.volcengine.ApiClient;
import com.volcengine.auth.CredentialProvider;
import com.volcengine.auth.OidcCredentialProvider;

public class SampleCode {
    public static void main(String[] args) throws Exception {
        // Required:
        // VOLCENGINE_OIDC_ROLE_TRN
        // VOLCENGINE_OIDC_TOKEN_FILE
        OidcCredentialProvider oidcProvider = OidcCredentialProvider.fromEnvironment();
        CredentialProvider credentialProvider = new CredentialProvider(oidcProvider);

        ApiClient apiClient = new ApiClient()
            .setCredentialProvider(credentialProvider)
            .setRegion("cn-beijing");
    }
}

SAML (AssumeRoleWithSAML)

SamlCredentialProvider exchanges a SAML 2.0 assertion (returned by your IdP) for temporary STS credentials via AssumeRoleWithSAML. Credentials are auto-refreshed before expiration.

⚠️ Notes

  1. Least privilege.
  2. Reasonable TTL; recommended ≤ 1 hour.
  3. samlAssertion is the base64-encoded SAML Response returned by your IdP.
import com.volcengine.ApiClient;
import com.volcengine.auth.CredentialProvider;
import com.volcengine.auth.SamlCredentialProvider;

public class SampleCode {
    public static void main(String[] args) {
        SamlCredentialProvider samlProvider = new SamlCredentialProvider(
            "trn:iam::1234567890:role/YourRoleName",           // roleTrn
            "trn:iam::1234567890:saml-provider/MyIdp",         // samlProviderTrn
            "BASE64_ENCODED_SAML_RESPONSE_FROM_IDP",           // samlAssertion
            null,                                              // rolePolicy (optional)
            null                                               // stsEndpoint (optional, uses default)
        );
        // Optional setters
        samlProvider.setDurationSeconds(3600);          // Credential TTL in seconds, default: 3600
        samlProvider.setExpireBufferSeconds(300);        // Expire buffer in seconds, default: 300
        samlProvider.setSchema("https");                // STS scheme, default: https
        samlProvider.setMaxRetries(3);                  // Retry attempts, default: 3, 0 disables retry
        samlProvider.setRetryIntervalMs(1000);          // Retry interval in ms, default: 1000
        // Proxy / TLS for reaching STS (optional)
        // samlProvider.setProxyUrl("http://user:pass@10.0.0.1:8080"); // HTTP forward proxy; empty uses client STS-scheme fallback, then JVM ProxySelector, not proxy env vars
        // samlProvider.setCaFile("/path/to/ca.pem");                  // PEM CA; empty + insecureSkipVerify=false uses original transport TLS, possibly custom
        // samlProvider.setInsecureSkipVerify(false);                  // Pass true to skip STS TLS verification; debugging only, default false, never in production

        CredentialProvider credentialProvider = new CredentialProvider(samlProvider);
        ApiClient apiClient = new ApiClient()
            .setCredentialProvider(credentialProvider)
            .setRegion("cn-beijing");
    }
}

Environment Variable Credential Provider

EnvironmentVariableCredentialProvider reads:

  • VOLCENGINE_ACCESS_KEY
  • VOLCENGINE_SECRET_KEY
  • VOLCENGINE_SESSION_TOKEN (optional)
import com.volcengine.ApiClient;
import com.volcengine.auth.CredentialProvider;
import com.volcengine.auth.EnvironmentVariableCredentialProvider;

public class SampleCode {
    public static void main(String[] args) {
        CredentialProvider credentialProvider =
            new CredentialProvider(new EnvironmentVariableCredentialProvider());

        ApiClient apiClient = new ApiClient()
            .setCredentialProvider(credentialProvider)
            .setRegion("cn-beijing");
    }
}

CLI Config Credential Provider

CLIConfigCredentialProvider reads $HOME/.volcengine/config.json by default.

  • Config path priority: constructor configPath > VOLCENGINE_CLI_CONFIG_FILE > $HOME/.volcengine/config.json
  • Profile priority: constructor profileName > VOLCENGINE_PROFILE > current in config > default

Supported profile mode:

  • AK / empty
  • StsToken
  • iamrole (delegates to StsAssumeRoleProvider)
    • Required: access-key, secret-key, role-name, account-id
    • Optional: session-token — when the source access-key / secret-key are themselves STS temporaries (e.g. issued by SSO/OIDC), this token is forwarded to the chained AssumeRole call as X-Security-Token.
  • OIDC (delegates to OidcCredentialProvider)
  • EcsRole (delegates to EcsRoleCredentialProvider)
  • SSO (reads STS credentials from the CLI sso cache; SDK refreshes the access token in memory by default; refreshCliCredentials refreshes and writes back to the cache)
  • console-login (reads STS credentials from the CLI console-login cache; SDK refreshes via OAuth refresh_token in memory by default; refreshCliCredentials refreshes and writes back to the cache)

Mode matching is case-insensitive.

import com.volcengine.ApiClient;
import com.volcengine.auth.CLIConfigCredentialProvider;
import com.volcengine.auth.CredentialProvider;

import java.nio.file.Paths;

public class SampleCode {
    public static void main(String[] args) {
        CLIConfigCredentialProvider cliProvider =
            new CLIConfigCredentialProvider("prod", Paths.get(System.getProperty("user.home"), ".volcengine", "config.json").toString());
        CredentialProvider credentialProvider = new CredentialProvider(cliProvider);

        ApiClient apiClient = new ApiClient()
            .setCredentialProvider(credentialProvider)
            .setRegion("cn-beijing");
    }
}

Runtime Refresh Behavior (sso / console-login)

For sso and console-login modes the SDK offers two ways to refresh:

  • Default (CLIConfigCredentialProvider / default credential chain): in-memory refresh only. On each credential expiry the SDK re-reads config.json and rebuilds the credential delegate, so profile, mode or AK changes are picked up at the next refresh boundary; it also re-reads ~/.volcengine/login/cache/*.json (console-login) or ~/.volcengine/sso/cache/*.json (SSO). If the cached access_token is not within its expiry buffer (60 seconds) it is used as is; otherwise the SDK exchanges the cached refresh_token at the OAuth /token endpoint and keeps the result in memory without writing any file or creating a lock file. SSO then calls the Portal GetRoleCredentials API for the STS triple.
  • Explicit refresh (CLIConfigCredentialProvider.refreshCliCredentials): refresh and write back. Intended for command-line tools that reuse CLI credentials: call it at the start of each command. When the access_token has expired it is renewed and written back to the cache, so later processes (including the default mode) reuse it instead of refreshing again. The returned CLIRefreshResult carries the credentials (getValue()) plus isRefreshed(), isPersisted() and getPersistError(). Other modes do not use a token cache and return their credentials directly.

The explicit refresh follows the shared cache protocol used by ve and the SDKs in every language (see CLITokenCacheStore.java):

  • OAuth refreshes are not locked. The write-back holds <cache file>.lock (created atomically with CREATE_NEW). If the lock exists the write-back is skipped; a lock file older than 10 seconds (by modification time) is treated as stale, removed, and acquisition is retried once. The cache is re-read under the lock. Right before the final rename the SDK checks again that the lock is still its own and the cache is byte-identical to what it re-read; if ve login / ve logout ran in between, the write-back is skipped (credentials are still returned). This narrows, but cannot fully close, the window against a concurrent login / logout: in rare timing, a cache may reappear once after logout, or one new login may be overwritten; simply run ve logout / ve login again.
  • A deleted cache (ve logout / ve sso logout) is not recreated, and a cache already updated by another process is left untouched. In both cases, and when another process holds the lock, isPersisted() is false and getPersistError() is null.
  • The write is based on the latest content on disk, updates only the refreshed fields, preserves all other fields verbatim (including big integers), and replaces the whole file through a temp file in the same directory and an atomic rename (mode 0600), so concurrent writers never corrupt it; the last replacement wins.
  • If the write-back fails (read-only directory, disk full, ...), getPersistError() reports the cause; the returned credentials are still valid, the cache file is left unchanged, and the next process refreshes again.
  • For long-lived credential objects, use CLIConfigCredentialProvider.createPersistent(profileName, configPath) (wrapped in a CredentialProvider as usual); the first retrieval and later renewals are written back, and getLastPersistError() reports the latest write-back failure.
  • Login / logout style tools that write or delete a cache can use CLITokenCacheStore.saveTokenCacheFile / removeTokenCacheFile: they remove the lock file first and then write or delete the cache atomically, without waiting for the lock.
  • The SDK never writes config.json; SSO role STS credentials stay in memory.

Behavior common to both modes:

  • Logout: once the cache is deleted, the SDK no longer renews with the in-memory refresh_token; the next refresh fails with an error pointing at ve login (console-login) or ve sso login (SSO). STS credentials already obtained remain usable until they expire.
  • Refresh-token rejection: when the authorization service rejects the refresh_token, the SDK raises an error instructing the user to run ve login (console-login) or ve sso login (SSO).
  • Concurrency: refreshes are serialized within a process by the CredentialProvider read-write lock.
import com.volcengine.auth.CLIConfigCredentialProvider;
import com.volcengine.auth.CLIRefreshResult;

CLIRefreshResult result = CLIConfigCredentialProvider.refreshCliCredentials(null, null); // default config file; profile: VOLCENGINE_PROFILE > current > "default"
if (result.getPersistError() != null) {
    // credentials are usable; they just could not be written back
}
System.out.println(result.getValue().getAk());

CLI-or-Default Credential Provider

CLIOrDefaultCredentialProvider selects credentials the same way the ve CLI does for an API call: a CLI profile when one is selected, otherwise the default credential chain. Use it in tools that should pick credentials like ve.

The selection happens once, in the constructor:

  1. Config file: constructor configPath > VOLCENGINE_CLI_CONFIG_FILE > $HOME/.volcengine/config.json (same as CLIConfigCredentialProvider). A missing file means there is no config. A file that cannot be read, is not valid JSON, or whose current / profiles have the wrong JSON type is also treated as no config, as the CLI ignores a config file it cannot decode.
  2. Explicit profileName (trimmed, non-empty): the profile must exist in the config file, otherwise the constructor throws ApiException with the message profile '<name>' not found in config file. Source: explicit.
  3. Otherwise the profile name is current in the config file, else VOLCENGINE_PROFILE, else VOLCSTACK_PROFILE (current takes precedence over the environment variables). If that profile exists it is used (source current, env:VOLCENGINE_PROFILE or env:VOLCSTACK_PROFILE); if it does not exist, the default chain is used. This is not an error.
  4. A selected profile is resolved by CLIConfigCredentialProvider with the profile name passed explicitly, so environment credentials such as VOLCENGINE_ACCESS_KEY / VOLCENGINE_SECRET_KEY never override it.
  5. Without a profile: if VOLCENGINE_DISABLE_DEFAULT_CREDENTIALS is exactly true the constructor throws ApiException; otherwise DefaultCredentialProvider is used (source default-chain). Its CLIConfigCredentialProvider step keeps its own profile order described above.

getProfileName() (null for the default chain), getSource() and usesDefaultChain() report the selection. Refreshes stay in memory and no file is written; to write refreshed sso / console-login tokens back to the token cache, use CLIConfigCredentialProvider.refreshCliCredentials.

import com.volcengine.ApiClient;
import com.volcengine.auth.CLIOrDefaultCredentialProvider;
import com.volcengine.auth.CredentialProvider;

public class SampleCode {
    public static void main(String[] args) throws Exception {
        // null: no explicit profile; null: default config file
        CLIOrDefaultCredentialProvider provider = new CLIOrDefaultCredentialProvider(null, null);
        System.out.println(provider.getSource() + " " + provider.getProfileName());

        ApiClient apiClient = new ApiClient()
            .setCredentialProvider(new CredentialProvider(provider))
            .setRegion("cn-beijing");
    }
}

ECS Role Credential Provider

EcsRoleCredentialProvider reads temporary credentials from ECS IMDS.

  • Role name priority: constructor arg > VOLCENGINE_ECS_METADATA > auto-detect from IMDS
  • Disable switch: VOLCENGINE_ECS_METADATA_DISABLED=true
import com.volcengine.ApiClient;
import com.volcengine.auth.CredentialProvider;
import com.volcengine.auth.EcsRoleCredentialProvider;

public class SampleCode {
    public static void main(String[] args) throws Exception {
        // Pass null or empty string to read VOLCENGINE_ECS_METADATA or auto-detect the role name from IMDS.
        EcsRoleCredentialProvider ecsProvider = EcsRoleCredentialProvider.create("your-ecs-role-name");
        // Optional setters
        ecsProvider.setMaxRetries(3);                   // Retry attempts, default: 3, 0 disables retry
        ecsProvider.setRetryIntervalMs(1000);           // Retry interval in ms, default: 1000
        ecsProvider.setConnectTimeoutMs(1000);           // Connect timeout in ms, default: 1000
        ecsProvider.setReadTimeoutMs(1000);              // Read timeout in ms, default: 1000
        ecsProvider.setExpireBufferSeconds(300);          // Expire buffer in seconds, default: 300

        CredentialProvider credentialProvider = new CredentialProvider(ecsProvider);
        ApiClient apiClient = new ApiClient()
            .setCredentialProvider(credentialProvider)
            .setRegion("cn-beijing");
    }
}

STS validation and diagnostics

AssumeRole, OIDC, and SAML accept only nonempty string AccessKeyId, SecretAccessKey, and SessionToken values inside Result.Credentials. OIDC/SAML also require a nonempty string Expiration that parses as an instant or offset date-time. Validation completes before updating credentials and expiration; failure leaves any previous cache intact. AssumeRole retains its existing duration-based cache expiration.

STS business errors (including HTTP 200), empty/null/nonstandard responses, JSON failures, and invalid credentials expose actual HTTP status, service code or an explicit classification, RequestId, headers, original bytes, and any underlying cause through ApiException and ErrorUtils.PrintError. OIDC token-file failures retain the file-read cause and have no STS response. The default credential chain retains each failed provider as a suppressed exception so diagnostics can expand all attempts.

ApiClient.setSimpleError(true) applies code: message display to SDK response errors and its bound built-in STS providers, including default-chain OIDC and CLI iamrole / oidc modes used directly or through the default chain. CLI applies explicitly configured values before the delegate's first STS request, updates its current built-in STS delegate when the setting changes, and retains the value when rebuilding delegates on refresh; setting false restores the existing display. Each built-in STS provider also supports setSimpleError(boolean) for direct configuration; explicitly configured client values override it. This setting does not change transport/proxy selection or cache identity. An allowed retry for a service expiry error forces the SDK-owned STS cache to refresh before signing again. Custom Provider implementations require no new methods and are not forcibly invalidated. See Retry and Error Handling.

STS reads compare received bytes with a known, untransformed body length. An incomplete read raises ReadError, preserves delivered bytes with body_complete=false, and prevents publishing credentials. A silent early EOF produces an EOFException; transport read failures retain their original cause. This applies to direct and proxied form requests; unknown-length or chunked responses retain stream completion semantics.

The four expiry codes trigger a default business-call retry only for the refreshable built-in STS cache used in that signing attempt. Static/environment/CLI AK credentials and STS exchanges do not retry solely for an expired source credential; independent transient failures remain retryable. OIDC/SAML form requests use buffered request output so complete 401/403/407 error bodies can be read, while response-length validation still detects real truncation.

Default Credential Provider

When credentials and credentialProvider are both unset, the SDK automatically uses DefaultCredentialProvider — no manual configuration is needed.

You can also explicitly set it if you need to customize options (e.g., roleName).

Default chain order:

  1. EnvironmentVariableCredentialProvider
  2. OidcCredentialProvider (from OIDC env vars)
  3. CLIConfigCredentialProvider
  4. EcsRoleCredentialProvider

reuseLastProviderEnabled is true by default.

import com.volcengine.ApiClient;
import com.volcengine.auth.CredentialProvider;
import com.volcengine.auth.DefaultCredentialProvider;

public class SampleCode {
    public static void main(String[] args) {
        DefaultCredentialProvider defaultProvider = DefaultCredentialProvider.builder()
            .reuseLastProviderEnabled(true)
            .roleName(null) // optional: used by ECS provider
            .build();
        // Or: DefaultCredentialProvider defaultProvider = DefaultCredentialProvider.create();

        CredentialProvider credentialProvider = new CredentialProvider(defaultProvider);
        ApiClient apiClient = new ApiClient()
            .setCredentialProvider(credentialProvider)
            .setRegion("cn-beijing");
    }
}

← Overview | Credentials(中文) | Endpoint →