← Overview | Credentials(中文) | Endpoint →
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.
⚠️ NoteEnvironment variables configured with
exportare 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.
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.
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_KEYValue: ***** |
| AccessKey Secret | Name: VOLCENGINE_SECRET_KEYValue: ***** |
| Session Token | Name: VOLCENGINE_SESSION_TOKENValue: ***** |
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
/Mmeans system-level variables. You may omit it for user-level variables.
| 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 |
- Basic credentials:
VOLCENGINE_ACCESS_KEYVOLCENGINE_SECRET_KEYVOLCENGINE_SESSION_TOKEN
- OIDC:
VOLCENGINE_OIDC_ROLE_TRNVOLCENGINE_OIDC_TOKEN_FILEVOLCENGINE_OIDC_ROLE_SESSION_NAMEVOLCENGINE_OIDC_ROLE_POLICYVOLCENGINE_OIDC_STS_ENDPOINT
- CLI config:
VOLCENGINE_CLI_CONFIG_FILEVOLCENGINE_PROFILEVOLCSTACK_PROFILE(fallback ofVOLCENGINE_PROFILE, used byCLIOrDefaultCredentialProvider)VOLCENGINE_DISABLE_DEFAULT_CREDENTIALS(CLIOrDefaultCredentialProvideronly)
- ECS metadata:
VOLCENGINE_ECS_METADATAVOLCENGINE_ECS_METADATA_DISABLED
For full details, see Environment Variables.
AK/SK is a pair of permanent access keys created in the Volcengine console. The SDK signs each request to authenticate.
⚠️ Notes
- Do not embed or expose AK/SK in client-side applications.
- Use a configuration center or environment variables.
- 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 (Security Token Service) provides temporary credentials (temporary AK/SK and Token).
⚠️ Notes
- Least privilege.
- 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);
}
}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");
}
}The following proxy/TLS rules apply to StsAssumeRoleProvider, OidcCredentialProvider, and SamlCredentialProvider:
proxyUrlsupports only HTTP forward proxies:http://[user:password@]host:port, with an explicit port in1..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 defaultProxySelector, including JVMhttp.proxyHost/http.proxyPortandhttps.proxyHost/https.proxyPortsystem properties. They do not parseHTTP_PROXY/HTTPS_PROXYor 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=0sends one attempt if the server closes after receiving the form without responding;npermits at mostn+1SDK 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
caFiletogether withinsecureSkipVerify=falseremoves 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=truetakes precedence overcaFile; 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 supports dynamic credentials with auto refresh.
⚠️ Notes
- Least privilege.
- Choose a reasonable TTL; maximum is 12 hours.
- 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);
}
}OidcCredentialProvider gets temporary credentials from STS via OIDC token.
Reference: https://www.volcengine.com/docs/6257/1494877
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);
}
}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");
}
}SamlCredentialProvider exchanges a SAML 2.0 assertion (returned by your IdP) for temporary STS credentials via AssumeRoleWithSAML. Credentials are auto-refreshed before expiration.
⚠️ Notes
- Least privilege.
- Reasonable TTL; recommended ≤ 1 hour.
samlAssertionis 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");
}
}EnvironmentVariableCredentialProvider reads:
VOLCENGINE_ACCESS_KEYVOLCENGINE_SECRET_KEYVOLCENGINE_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");
}
}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>currentin config >default
Supported profile mode:
AK/ emptyStsTokeniamrole(delegates toStsAssumeRoleProvider)- Required:
access-key,secret-key,role-name,account-id - Optional:
session-token— when the sourceaccess-key/secret-keyare themselves STS temporaries (e.g. issued by SSO/OIDC), this token is forwarded to the chained AssumeRole call asX-Security-Token.
- Required:
OIDC(delegates toOidcCredentialProvider)EcsRole(delegates toEcsRoleCredentialProvider)SSO(reads STS credentials from the CLI sso cache; SDK refreshes the access token in memory by default;refreshCliCredentialsrefreshes and writes back to the cache)console-login(reads STS credentials from the CLI console-login cache; SDK refreshes via OAuthrefresh_tokenin memory by default;refreshCliCredentialsrefreshes 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");
}
}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-readsconfig.jsonand 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 cachedaccess_tokenis not within its expiry buffer (60 seconds) it is used as is; otherwise the SDK exchanges the cachedrefresh_tokenat the OAuth/tokenendpoint and keeps the result in memory without writing any file or creating a lock file. SSO then calls the PortalGetRoleCredentialsAPI 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 theaccess_tokenhas expired it is renewed and written back to the cache, so later processes (including the default mode) reuse it instead of refreshing again. The returnedCLIRefreshResultcarries the credentials (getValue()) plusisRefreshed(),isPersisted()andgetPersistError(). 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; ifve login/ve logoutran 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 runve logout/ve loginagain. - 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()isfalseandgetPersistError()isnull. - 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 aCredentialProvideras usual); the first retrieval and later renewals are written back, andgetLastPersistError()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 atve login(console-login) orve 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 runve login(console-login) orve sso login(SSO). - Concurrency: refreshes are serialized within a process by the
CredentialProviderread-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());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:
- Config file: constructor
configPath>VOLCENGINE_CLI_CONFIG_FILE>$HOME/.volcengine/config.json(same asCLIConfigCredentialProvider). A missing file means there is no config. A file that cannot be read, is not valid JSON, or whosecurrent/profileshave the wrong JSON type is also treated as no config, as the CLI ignores a config file it cannot decode. - Explicit
profileName(trimmed, non-empty): the profile must exist in the config file, otherwise the constructor throwsApiExceptionwith the messageprofile '<name>' not found in config file.Source:explicit. - Otherwise the profile name is
currentin the config file, elseVOLCENGINE_PROFILE, elseVOLCSTACK_PROFILE(currenttakes precedence over the environment variables). If that profile exists it is used (sourcecurrent,env:VOLCENGINE_PROFILEorenv:VOLCSTACK_PROFILE); if it does not exist, the default chain is used. This is not an error. - A selected profile is resolved by
CLIConfigCredentialProviderwith the profile name passed explicitly, so environment credentials such asVOLCENGINE_ACCESS_KEY/VOLCENGINE_SECRET_KEYnever override it. - Without a profile: if
VOLCENGINE_DISABLE_DEFAULT_CREDENTIALSis exactlytruethe constructor throwsApiException; otherwiseDefaultCredentialProvideris used (sourcedefault-chain). ItsCLIConfigCredentialProviderstep 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");
}
}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");
}
}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.
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:
EnvironmentVariableCredentialProviderOidcCredentialProvider(from OIDC env vars)CLIConfigCredentialProviderEcsRoleCredentialProvider
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 →