application.properties or an environment variable and carry on. On Amazon Bedrock and Azure OpenAI that step is optional, and in a company it is usually the step you are asked to remove. A key is a password with no owner. It works from any machine, it outlives the person who pasted it, and when it shows up in a log nobody can say which service used it.
This article wires Spring AI 2.1 to both clouds with no key, no secret key and no password anywhere in the application. On AWS the application borrows an IAM role; on Azure it borrows a Microsoft Entra ID identity. Along the way it covers what Spring AI 2.1 did to the Azure OpenAI starter, the settings that make a keyless setup fail or quietly fall back to a key, and how to log who called which model without logging anything secret.
Read this before trusting any line below. I had no AWS account and no Azure subscription while writing this. Every “verified” result ran the real Spring AI, AWS SDK v2 and azure-identity code in a child JVM with the same environment variables a pod or an App Service container receives, against one local HTTP server that plays STS, Bedrock, the Azure identity endpoint and Azure OpenAI. That proves what the libraries send. It does not prove that real STS, Entra ID, Bedrock or Azure OpenAI accept it, and it says nothing about IAM policies, Azure RBAC, model access or latency. The policy and manifest files in the repository are examples I never applied. Where a claim comes from AWS or Microsoft documentation instead of a run, the text says so.
Versions tested. Spring Boot 4.2.0 and Spring AI 2.1.0 (both released 19 November 2026, per Maven Central), AWS SDK for Java v2 2.55.14 (the version Spring AI 2.1.0 resolves; Maven Central already has 2.59.11), azure-identity 1.19.0, Temurin 25.0.5.1 (Java 25, the current LTS). Companion code: asmhatre/spring-ai, module cloud-providers.
A key is something you have; an identity is something the platform says you are
Start with what “keyless” means, because it is not “no authentication”. The request to Bedrock or Azure OpenAI is still authenticated. What changes is where the proof comes from. With a key, the proof is a secret you stored. Without one, the proof is issued to your workload by the platform it runs on, lasts minutes to an hour, and can be switched off from one place. On AWS the proof is a temporary credential: an access key id that starts withASIA, a secret, and a session token, obtained from STS by presenting a token the platform gave your pod. Every request is then signed with it (Signature Version 4). On Azure the proof is a bearer token, a JWT from Microsoft Entra ID, obtained by asking a local identity endpoint that the platform provides to your container. Either way your code never sees a long-lived secret.
- AWS: the default credentials provider chain and IAM roles for service accounts (IRSA)
- Azure: managed identities on App Service and the azure-identity library
- The same idea applied to a different secret: Securing an MCP Server with Spring Security 7
Bedrock: the smallest working setup has no credential code at all
Spring AI talks to Bedrock through the Converse API (the model class isBedrockProxyChatModel). The starter brings the AWS SDK with it, so the dependency list is one line for Bedrock, one for the OpenAI starter you will need for Azure later, and azure-identity. The full pom.xml parent is Spring Boot 4.2.0 with the Spring AI 2.1.0 BOM imported.
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-bedrock-converse</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-openai</artifactId>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.19.0</version>
</dependency>
The configuration is the part to look at, because of what is missing. This is the whole application-bedrock.properties:
app.provider=bedrock
spring.ai.model.chat=bedrock-converse
# Example model id; not validated against a real account (see the README).
spring.ai.bedrock.converse.chat.options.model=us.anthropic.claude-sonnet-4-5-20250929-v1:0
# No access-key / secret-key / session-token anywhere: the default credentials provider chain supplies them.
app.model=${spring.ai.bedrock.converse.chat.options.model}
No access-key, no secret-key, no session-token. Spring AI’s Bedrock auto-configuration then builds the AWS default credentials provider chain and hands it to the Bedrock client. (I read this from the bytecode of BedrockAwsConnectionConfiguration: static keys if both properties are set, a named profile if one is set, otherwise DefaultCredentialsProvider. Output 03 below proves the first of those.) The model id is an example I did not check against a real account.
To see it work without an AWS account, the test starts the application in a child JVM with exactly the environment EKS gives a pod that uses IRSA: AWS_ROLE_ARN and AWS_WEB_IDENTITY_TOKEN_FILE, plus AWS_REGION (which I set in every run; I did not confirm from AWS’s documentation that the webhook sets it, so check kubectl describe pod). The endpoints are pointed at the local server with the SDK’s own AWS_ENDPOINT_URL_* variables. The test is BedrockTest.java and the transcript is 01-bedrock-irsa.txt:
STS received 1 AssumeRoleWithWebIdentity call(s) (1 GetCallerIdentity for the audit identity)
Authorization header on AssumeRoleWithWebIdentity: null (this call is not signed)
RoleArn = arn:aws:iam::111122223333:role/spring-ai-bedrock
RoleSessionName starts with = aws-sdk-java-
WebIdentityToken equals the token file content: true
Bedrock received POST /model/us.anthropic.claude-sonnet-4-5-20250929-v1:0/converse
signed by access key id : ASIASTUB0000... (temporary: starts with ASIA)
signing service / region: bedrock / us-east-1
x-amz-security-token signed: true
X-Amz-Security-Token header present: true
Read it top to bottom. STS was called once, with the role ARN and the web identity token from the file, and that call is not signed: the token is the proof. STS answered with temporary credentials, and the Bedrock request was then signed by an access key id beginning ASIA (the stub invents its keys, but the prefix is how you recognise a temporary one) with the session token included in the signature. The one extra STS call is GetCallerIdentity, which the audit advisor makes once; more on that in the audit section.
- The whole child-process harness: AppProcess.java and the stub LocalCloud.java (details in the accordion at the end).
- Why the application is unchanged between IRSA and Pod Identity: next section.
- Spring AI reference: Bedrock Converse
How the AWS chain decides who you are, and why the order matters
The default chain is a list of places to look, tried in order, and the first one that returns credentials wins. I did not have to guess the order: when no credentials exist, the SDK prints it. Here is the start of the real error from 04-bedrock-no-credentials.txt (a run with no AWS variables at all; the full line is in the accordion at the end):FAILED 1: SdkClientException / root cause SdkClientException: Unable to load credentials from any of the providers in the chain AwsCredentialsProviderChain(credentialsProviders=[SystemPropertyCredentialsProvider(), EnvironmentVariableCredentialsProvider(), WebIdentityTokenFileCredentialsProvider(), ProfileCredentialsProvider(profileName=default…
access-key and secret-key properties before it builds the chain at all. Rows 3 and 5 are the two keyless routes on Kubernetes. Row 3 is IRSA, which exchanges the pod’s projected service account token with AssumeRoleWithWebIdentity; it needs an OIDC provider registered for the cluster and a trust policy naming the service account. Row 5 is EKS Pod Identity, which needs no OIDC provider: the cluster runs an agent, the pod gets AWS_CONTAINER_CREDENTIALS_FULL_URI, and the SDK fetches credentials from it using a token file as the authorization header (AWS’s comparison). Row 6 is EC2’s instance profile.
The application is identical for all of them. Only the environment changes. This is the Pod Identity run from 06-bedrock-pod-identity.txt, same jar, no AWS_ROLE_ARN:
ANSWER 1: Hello from the Bedrock stub.
Credentials endpoint calls : 1
Authorization header equals the token file : true
AssumeRoleWithWebIdentity calls : 0
Bedrock request signed by : ASIAPODID000...
Two details worth taking from it. The credentials endpoint was called once, with an Authorization header equal to the contents of the token file, and STS was never asked to assume anything, because on Pod Identity the cluster has already done that. The deploy files for both routes (eks-irsa.yaml, irsa-trust-policy.json, pod-identity-trust-policy.json, eks-pod-identity.sh) are in an accordion below. They are examples; I never applied them.
- The Pod Identity trust policy (principal
pods.eks.amazonaws.com, actionssts:AssumeRoleandsts:TagSession) is quoted from AWS’s page on the role - Local development is the same chain with a different row: an SSO profile (
spring.ai.bedrock.aws.profile.nameexists in the auto-configuration metadata). I did not run that path.
What goes wrong on the Bedrock side
Each of these cost a test or a surprise while writing the companion module, and each produces a working application, which is why they are dangerous. Nothing throws. The request just goes out signed by something other than what you intended, or for a different region.A leftover key beats the role
Rows 1, 2 and Spring AI’s own properties all sit above IRSA. The run in 03-bedrock-precedence.txt sets the IRSA variables every time and adds one more source:IRSA variables are set in all three runs. What signs the Bedrock request?
nothing else -> ASIASTUB0000001 AssumeRoleWithWebIdentity calls: 1
AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY set -> AKIALEFTOVERENVKEY1 AssumeRoleWithWebIdentity calls: 0
spring.ai.bedrock.aws.access-key/secret-key -> AKIALEFTOVERPROPKEY AssumeRoleWithWebIdentity calls: 0
With a stray AWS_ACCESS_KEY_ID in the environment, or an access-key property someone forgot to delete, the request is signed by that key and STS is never called. The application works, the audit trail says the key did it, and nobody notices that the role is unused. The audit advisor below exposes this: the principal it logs would be an IAM user, not the assumed role.
Check this in CI, not by eye. The cheapest guard is a startup assertion that fails ifspring.ai.bedrock.aws.access-keyis set under the production profile, and a deployment rule that noAWS_ACCESS_KEY_IDexists in the pod spec. The audit line’s principal is the runtime check: in production it should always be anassumed-roleARN.
AWS_REGION is ignored, and the fix is one bean
Spring AI’sspring.ai.bedrock.aws.region property defaults to us-east-1, and the auto-configuration only falls back to the SDK’s region chain when that property is blank. So a pod with AWS_REGION=eu-west-1 still signs for us-east-1 (02-bedrock-region-trap.txt):
AWS_REGION=eu-west-1 in the environment in all four runs.
nothing else set -> Bedrock request signed for region us-east-1
spring.ai.bedrock.aws.region=${AWS_REGION} -> Bedrock request signed for region eu-west-1
spring.ai.bedrock.aws.region=eu-west-1 -> Bedrock request signed for region eu-west-1
own AwsRegionProvider bean (DefaultAwsRegionProviderChain) -> Bedrock request signed for region eu-west-1
Both the region provider and the credentials provider beans are @ConditionalOnMissingBean (read with javap -v), so you can replace the region logic with one bean. This is BedrockRegionFromEnvConfig.java, and the last row of the output above is it working:
@Configuration
@Profile("bedrock-region-env")
class BedrockRegionFromEnvConfig {
@Bean
AwsRegionProvider regionProvider() {
return DefaultAwsRegionProviderChain.builder().build();
}
}
Setting spring.ai.bedrock.aws.region=${AWS_REGION} in the properties also works (row two). The point is that nothing tells you the default exists until a model in the wrong region says it is not enabled for your account.
No credential source at all
On a laptop, or in a pod whose service account was never annotated, no row has anything. The call fails with the chain error shown above, and the application still writes an audit line, with the principal marked unresolved (04-bedrock-no-credentials.txt):WARN audit - provider=bedrock principal=unresolved model=us.anthropic.claude-sonnet-4-5-20250929-v1:0 outcome=FAILED error=SdkClientException ms=<n>
Temporary credentials expire, and a short lifetime means a refetch per call
The credentials from STS last for the role session duration (an hour is typical), and the SDK caches them and refreshes shortly before they expire. I wanted to know how short a lifetime has to be before that stops helping, so 05-bedrock-credential-refresh.txt asks for five Bedrock calls at three lifetimes:STS credential lifetime AssumeRoleWithWebIdentity distinct access key ids on Bedrock calls
3600 s 1 1 (of 5 calls)
300 s 1 1 (of 5 calls)
30 s 6 5 (of 5 calls)
At one hour and at five minutes the SDK called STS once for five calls. At thirty seconds it called STS six times (one for the audit identity call, then once per request) and every request was signed by a different access key. I did not find the exact threshold, only that 30 seconds is below it and 300 is above; if your role session duration is short, expect an STS round trip on the request path.
The OpenAI starter breaks startup even though you only use Bedrock
Chat is selected withspring.ai.model.chat=bedrock-converse, but every other modality (audio speech, transcription, embedding, image, moderation) still defaults to OpenAI. With the OpenAI starter on the classpath for Azure, a Bedrock-only run dies at startup asking for an OpenAI key. This module sets those to none in application.properties. The failure, from 11-startup-trap.txt:
with spring.ai.model.audio.speech=none (this module's setting): exit 0
with spring.ai.model.audio.speech unset (the default, here set to its default value openai): exit 1
- Every scenario in this section is a test in BedrockTest.java; each figure above is an assertion there.
- Spring AI 2.1 reference on provider switching: Anthropic Claude vs OpenAI vs Gemini in Spring AI 2.0
Azure OpenAI in Spring AI 2.1: the dedicated starter is gone
If you search for “Spring AI Azure OpenAI” you will findspring-ai-starter-model-azure-openai and a lot of 1.x tutorials built on it. In 2.1 it is not there. 00-azure-starter.txt comes from azure-starter-check.sh, which reads Maven Central and then asks Maven to resolve the starter without a version under the 2.1.0 BOM:
A. Versions on Maven Central (maven-metadata.xml)
spring-ai-starter-model-azure-openai newest listed version=2.0.0-M4
spring-ai-starter-model-openai newest listed version=2.1.0
spring-ai-starter-model-bedrock-converse newest listed version=2.1.0
B. Does the Spring AI 2.1.0 BOM manage the Azure starter?
spring-ai-starter-model-azure-openai NOT managed
spring-ai-azure-openai NOT managed
spring-ai-starter-model-openai managed
spring-ai-starter-model-bedrock-converse managed
C. Maven asked to resolve the Azure starter with no version under that BOM
'dependencies.dependency.version' for org.springframework.ai:spring-ai-starter-model-azure-openai:jar is missing. @ line 4, column 27
The newest published version of the Azure starter is the milestone 2.0.0-M4; the BOM does not manage it. Spring AI’s own Azure OpenAI reference page says: “As of Spring AI 2.0.0-M5, [OpenAI Chat] should be use to access OpenAI models deployed on Azure / Microsoft Foundry.” (the typo is theirs). So on 2.1 you use the OpenAI starter, which is built on the official OpenAI Java SDK, and tell it the endpoint is Azure.
Azure, two ways: properties only, or a credential you choose
Spring AI 2.1 decides it is talking to Azure whenspring.ai.openai.microsoft-foundry is true, or when the base URL has the host name openai.azure.com or cognitiveservices.azure.com in it (I read those strings in the bytecode of OpenAiSetup, not the exact comparison; my stub is on 127.0.0.1, so I set the property). If it is Azure and there is no API key, it uses Entra ID. This is the properties-only setup, application-azure-default.properties:
app.provider=azure
spring.ai.model.chat=openai
spring.ai.openai.microsoft-foundry=true
spring.ai.openai.base-url=${AZURE_OPENAI_ENDPOINT:https://my-resource.openai.azure.com/openai/v1}
spring.ai.openai.chat.options.deployment-name=${AZURE_OPENAI_DEPLOYMENT:gpt-4o-mini}
spring.ai.openai.chat.options.model=${AZURE_OPENAI_DEPLOYMENT:gpt-4o-mini}
# No api-key and no credential: azure-identity on the classpath makes Spring AI use DefaultAzureCredential.
app.model=${spring.ai.openai.chat.options.deployment-name}
No key, no credential. With azure-identity on the classpath, OpenAiSetup builds a DefaultAzureCredential, asks it for tokens with the scope https://cognitiveservices.azure.com/.default, and caches each token until five minutes before it expires (all three read with javap -c from AzureInternalOpenAiHelper). The base URL ends in /openai/v1, which the code maps to the unified URL path; anything else is treated as the legacy deployment-based path.
DefaultAzureCredential is a chain: environment variables, workload identity, managed identity, then developer tools such as the Azure CLI. That is convenient on a laptop and ambiguous in production, where you usually know exactly which identity you want. Spring AI exposes AzureOpenAiCredentials.from(TokenCredential) for that, and its reference page uses it. The catch I hit: the credential is a property of the auto-configuration (typed as the OpenAI SDK’s Credential), and I found no bean hook for it, so choosing your own means building the chat model yourself. This is AzureConfig.java:
@Bean
TokenCredential azureCredential(@Value("${app.azure.client-id:}") String clientId) {
var builder = new ManagedIdentityCredentialBuilder();
if (StringUtils.hasText(clientId)) {
builder.clientId(clientId);
}
return builder.build();
}
@Bean
OpenAiChatModel openAiChatModel(TokenCredential credential, @Value("${spring.ai.openai.base-url}") String baseUrl,
@Value("${spring.ai.openai.chat.options.deployment-name}") String deployment) {
OpenAiChatOptions options = OpenAiChatOptions.builder()
.microsoftFoundry(true)
.baseUrl(baseUrl)
.deploymentName(deployment)
.model(deployment)
.credential(AzureOpenAiCredentials.from(credential))
.build();
return OpenAiChatModel.builder().options(options).build();
}
Leave app.azure.client-id empty for a system-assigned identity, or set it for a user-assigned one. Because an OpenAiChatModel bean now exists, the auto-configured one backs off.
azure-identity and to the platform. The request that reaches Azure OpenAI carries a bearer token and no api-key header. This is what the stub recorded for both setups (07-azure-managed-identity.txt, JWT shortened by the test):
profile azure (exit 0)
INFO audit - provider=azure principal=oid=00000000-0000-0000-0000-00000000a11c,tid=11111111-2222-3333-4444-555555555555 model=gpt-4o-mini outcome=OK inputTokens=11 outputTokens=6 ms=<n>
ANSWER 1: Hello from the Azure stub.
identity endpoint calls : 1
identity request query : api-version=2019-08-01&resource=https://cognitiveservices.azure.com
chat request path : POST /openai/v1/chat/completions
Authorization : Bearer eyJhbG... (3 segments, 262 chars)
token claim aud : https://cognitiveservices.azure.com
request body model : gpt-4o-mini
api-key header : null
The identity request asked for resource=https://cognitiveservices.azure.com, the chat request went to /openai/v1/chat/completions with the deployment name as the model, and the header is a three-segment JWT. The azure-default profile produced the same request; its transcript section is in the same file.
The role you need, and the switch you want. Calling the model with Entra ID needs a data-plane role on the Azure OpenAI resource. Microsoft’s role-based access control page names Cognitive Services OpenAI User for “Make inference API calls with Microsoft Entra ID”, and says the management role Cognitive Services Contributor does not include it. Once the identity works, turn key authentication off on the resource (disableLocalAuth) so a leaked key stops being a way in. azure-setup.sh has the Azure CLI steps; I never ran them.
- Source of every Azure behaviour above: AzureConfig.java, AzureDefaultConfig.java and AzureTest.java
- Spring AI 2.1 reference: Azure OpenAI (“Custom Microsoft Entra credentials”)
- AKS pods use workload identity instead of an App Service identity: aks-workload-identity.yaml (not applied) and Microsoft’s overview.
What goes wrong on the Azure side
azure-identity is not optional, and the error says so
The OpenAI starter does not appear to bringazure-identity with it: its own error message tells you to add the library, and I added it explicitly in the pom. Remove it from the classpath and the Azure profile fails before any request is made (09-azure-without-azure-identity.txt; the test strips the jar from the child JVM’s classpath):
Microsoft Foundry was detected, but no credential was provided. If you want to use passwordless authentication, you need to add the Azure Identity library (groupId=`com.azure`, artifactId=`azure-identity`)
exit code: 1, identity endpoint calls: 0, chat calls: 0
Unlike most of the traps in this article, this one comes with a helpful message. The identity endpoint was never called and no chat request was sent.
A leftover API key in the environment turns Entra ID off
Spring AI’s setup code also readsMICROSOFT_FOUNDRY_API_KEY and OPENAI_API_KEY from the environment when no key is configured (detectApiKey in the bytecode). So a variable inherited from a base image, a CI template or someone’s shell silently decides the authentication. The properties-only profile with OPENAI_API_KEY set (07b-azure-leftover-api-key.txt):
profile azure-default, identity endpoint available, OPENAI_API_KEY=<leftover> set (exit 0)
INFO audit - provider=azure principal=DefaultAzureCredential(unresolved) model=gpt-4o-mini outcome=OK inputTokens=11 outputTokens=6 ms=<n>
ANSWER 1: Hello from the Azure stub.
identity endpoint calls : 0
api-key header : <leftover value, sent as is>
Authorization header : null
The identity endpoint was never called, the chat request carried the leftover value in an api-key header, and the call succeeded, so nothing looked wrong. The audit line shows principal=DefaultAzureCredential(unresolved), which is the only hint, and a good reason to prefer the explicit credential. I tested this on the azure-default profile only.
An unusable identity looks like a failed model call, not a failed login
When the identity endpoint refuses the request, the exception that reaches your code is aClientAuthenticationException from deep inside azure-identity, raised from chatClient.call(). Here the stub rejects the IDENTITY_HEADER (10-azure-identity-failure.txt; the error text is my stub’s, a real endpoint words it differently):
WARN audit - provider=azure principal=unresolved model=gpt-4o-mini outcome=FAILED error=ClientAuthenticationException ms=<n>
FAILED 1: ClientAuthenticationException / root cause MsalServiceException: [Managed Identity] Error Code: bad identity header Error Message: null
identity endpoint calls: 2, chat calls that reached the stub: 0
Two things to take from it. The identity endpoint was asked twice for one failed call (there appears to be a retry), and the audit advisor still logged the call, with the principal marked unresolved because the principal supplier needs the same token. If your alerting looks for audit lines with outcome=FAILED, this is how a broken managed identity shows up.
A token that lives under five minutes is fetched on every call
The 5-minute margin is Spring AI’s; a managed identity token normally lives much longer. But 08-azure-token-refresh.txt shows what happens when it does not. Five chat calls, three token lifetimes:# How often is the identity endpoint called? Five chat calls, three token lifetimes
token lifetime profile azure profile azure-default
3600 s 1 identity calls 1 identity calls
600 s 1 identity calls 1 identity calls
240 s 11 identity calls 10 identity calls
At one hour and at ten minutes, one identity call served all five chat calls. At four minutes there were ten or eleven, roughly two identity calls per chat call. I did not work out why it is two rather than one; the likely cause is the token cache inside azure-identity applying its own refresh window, but I did not inspect it. The practical rule: if you ever see the identity endpoint busy, check the token lifetime before blaming the model.
- Why the default chain is slower on a laptop than in a pod: the chain tries each source in turn (the identity-library documentation lists them). I did not time that path.
- Microsoft: use Azure OpenAI with managed identity
Audit logging: who called which model, without logging the secret
With a key, the log says a key was used. With an identity, the log can say which identity, and that is the whole point of the advisor below. AuditAdvisor.java is a Spring AICallAdvisor that writes one line per call to a logger named audit: provider, principal, model, outcome, token counts and milliseconds. It never touches the prompt, the completion or any credential.
public ChatClientResponse adviseCall(ChatClientRequest request, CallAdvisorChain chain) {
long start = System.nanoTime();
String who = resolvePrincipal();
try {
ChatClientResponse response = chain.nextCall(request);
var chatResponse = response.chatResponse();
String model = chatResponse != null && !chatResponse.getMetadata().getModel().isBlank()
? chatResponse.getMetadata().getModel() : configuredModel;
Usage usage = chatResponse != null ? chatResponse.getMetadata().getUsage() : null;
AUDIT.info("provider={} principal={} model={} outcome=OK inputTokens={} outputTokens={} ms={}",
provider, who, model,
usage != null ? usage.getPromptTokens() : null,
usage != null ? usage.getCompletionTokens() : null,
(System.nanoTime() - start) / 1_000_000);
return response;
}
catch (RuntimeException ex) {
AUDIT.warn("provider={} principal={} model={} outcome=FAILED error={} ms={}",
provider, who, configuredModel, ex.getClass().getSimpleName(),
(System.nanoTime() - start) / 1_000_000);
throw ex;
}
}
The principal is where the keyless design pays off. On Bedrock, BedrockConfig.java asks STS who the credentials provider currently resolves to (GetCallerIdentity, signed with the same provider) and logs the ARN. On Azure, AzureConfig.java reads the oid and tid claims out of the token for labelling only; nothing is validated there, because Azure does that. A failed identity lookup becomes principal=unresolved instead of hiding the call.
InvokeModel, InvokeModelWithResponseStream, Converse, ConverseStream) are logged by CloudTrail as management events, on by default (AWS: logging Bedrock with CloudTrail); I read that, I did not look at a real trail, and I did not check what Azure writes. This is what the application’s own lines look like across two calls on each cloud (12-audit-and-secret-hygiene.txt):
Audit lines from the Bedrock run (two calls, default log levels):
INFO audit - provider=bedrock principal=arn:aws:sts::111122223333:assumed-role/spring-ai-bedrock/pod-session model=us.anthropic.claude-sonnet-4-5-20250929-v1:0 outcome=OK inputTokens=12 outputTokens=7 ms=<n>
INFO audit - provider=bedrock principal=arn:aws:sts::111122223333:assumed-role/spring-ai-bedrock/pod-session model=us.anthropic.claude-sonnet-4-5-20250929-v1:0 outcome=OK inputTokens=12 outputTokens=7 ms=<n>
Audit lines from the Azure run (two calls, DEBUG on com.azure, MSAL, okhttp, Spring AI):
INFO audit - provider=azure principal=oid=00000000-0000-0000-0000-00000000a11c,tid=11111111-2222-3333-4444-555555555555 model=gpt-4o-mini outcome=OK inputTokens=11 outputTokens=6 ms=<n>
INFO audit - provider=azure principal=oid=00000000-0000-0000-0000-00000000a11c,tid=11111111-2222-3333-4444-555555555555 model=gpt-4o-mini outcome=OK inputTokens=11 outputTokens=6 ms=<n>
The Bedrock principal is the assumed-role ARN, with the session name the stub invented. Two replicas of one service share a role, so the ARN alone does not tell them apart; the real session name comes from the SDK (output 01 shows it starts with aws-sdk-java-) or from the platform. On Azure the oid is the object id of the managed identity, and two services that share an identity share it.
Does anything secret reach the log?
An audit trail is a liability if it records the credentials. So the test (CommonTest.java, transcript 12-audit-and-secret-hygiene.txt) runs each cloud, collects the whole output, and searches it for every secret the run handled: the STS secret key and session token, the projected web identity token, the Azure JWT and the identity header. It does this at default log levels and with DEBUG switched on:Searched each whole log for every secret the run handled:
Bedrock, default levels Bedrock, DEBUG on awssdk + Spring AI Azure, DEBUG
STS secret access key not found not found -
STS session token not found FOUND -
Web identity token (projected) not found not found -
Azure access token (JWT) - - not found
Azure token payload segment - - not found
IDENTITY_HEADER value - - not found
Prompt text not found not found not found
One real finding: the session token appears at DEBUG. Withlogging.level.software.amazon.awssdk=DEBUGthe SigV4 signer logs its canonical request, and that includesx-amz-security-token:followed by the live session token. The secret access key and the web identity token did not appear, so the token alone cannot sign a request, but it is still a credential and it is in your log aggregator. The excerpt is in the same transcript. Keep that logger at INFO in production, or filter it. The Azure DEBUG run produced only 49 lines (azure-coreand MSAL log little through SLF4J here), so “not found” for Azure is weak evidence; I did not test every logger.
- Chain order for advisors, and a PII-redacting one: Writing Custom Advisors in Spring AI 2.0
- Tokens and cost per call as metrics instead of log lines: Observability for Spring AI
- A per-tenant gateway in front of the provider: The LLM Gateway Pattern for Java Microservices
Should you do this at all?
Usually yes on the cloud that hosts the workload; no new security for free. If the application runs on EKS, ECS, EC2, App Service, Container Apps or AKS and calls the model in the same cloud, keyless is strictly better than a key in a secret store: nothing to rotate, nothing to leak from a config file. But it moves the risk rather than removing it. The IAM role or Azure role is now the thing to scope tightly (one model, notfoundation-model/*; one resource, not the subscription), and every pod that shares the role shares the blast radius. If the workload is on-premises or in a third cloud you need workload identity federation, which I did not cover or test. For local development, use your own SSO profile oraz login, not a shared key.
Further reading
- Companion repository: asmhatre/spring-ai, module cloud-providers (README, tests, every transcript)
- Spring AI 2.0 in 10 Minutes: ChatClient on Spring Boot 4.1
- Prompt Injection Defense in Spring AI (what a scoped identity does not protect you from)
- Prompt Caching in Spring AI
- Spring AI: Bedrock Converse, Spring AI: Azure OpenAI
- AWS: IAM roles for service accounts, AWS: EKS Pod Identity, AWS: Bedrock model invocation logging
- Microsoft: managed identities on App Service, AKS workload identity
Deploy files: IAM policy, trust policies, Kubernetes and Azure CLI (examples, never applied)
None of these was applied to a real account. They exist so every snippet has a file, and so the ids and names to replace are obvious. Check the Bedrock permissions in particular: the AWS page I read for the deny rules says a denied InvokeModel also blocks Converse, but I could not confirm from AWS documentation that allowing only InvokeModel and InvokeModelWithResponseStream is enough for Converse, so test it in a sandbox account.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "InvokeOneModelOnly",
"Effect": "Allow",
"Action": [
"bedrock:InvokeModel",
"bedrock:InvokeModelWithResponseStream"
],
"Resource": [
"arn:aws:bedrock:*::foundation-model/anthropic.claude-sonnet-4-5-20250929-v1:0",
"arn:aws:bedrock:us-east-1:111122223333:inference-profile/us.anthropic.claude-sonnet-4-5-20250929-v1:0"
]
}
]
}{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Federated": "arn:aws:iam::111122223333:oidc-provider/oidc.eks.us-east-1.amazonaws.com/id/EXAMPLED539D4633E53DE1B71EXAMPLE"
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"oidc.eks.us-east-1.amazonaws.com/id/EXAMPLED539D4633E53DE1B71EXAMPLE:aud": "sts.amazonaws.com",
"oidc.eks.us-east-1.amazonaws.com/id/EXAMPLED539D4633E53DE1B71EXAMPLE:sub": "system:serviceaccount:ai:spring-ai"
}
}
}
]
}pod-identity-trust-policy.json
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowEksAuthToAssumeRoleForPodIdentity",
"Effect": "Allow",
"Principal": { "Service": "pods.eks.amazonaws.com" },
"Action": [ "sts:AssumeRole", "sts:TagSession" ]
}
]
}# NOT APPLIED to a real cluster. Account id, OIDC provider id and names are examples.
# IRSA: the annotation is the whole link between the pod and the IAM role. The application sets no AWS key.
apiVersion: v1
kind: ServiceAccount
metadata:
name: spring-ai
namespace: ai
annotations:
eks.amazonaws.com/role-arn: arn:aws:iam::111122223333:role/spring-ai-bedrock
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: spring-ai
namespace: ai
spec:
replicas: 2
selector:
matchLabels: { app: spring-ai }
template:
metadata:
labels: { app: spring-ai }
spec:
serviceAccountName: spring-ai
containers:
- name: app
image: registry.example.com/spring-ai-cloud-providers:1.0.0
env:
- name: SPRING_PROFILES_ACTIVE
value: bedrock
# IRSA's webhook injects AWS_ROLE_ARN and AWS_WEB_IDENTITY_TOKEN_FILE (confirmed in AWS's docs); check with
# `kubectl describe pod` whether AWS_REGION is there too. Spring AI ignores AWS_REGION for Bedrock
# (output/02-bedrock-region-trap.txt), so set the region property explicitly:
- name: SPRING_AI_BEDROCK_AWS_REGION
value: us-east-1#!/usr/bin/env bash
# NOT RUN against a real account. Names and ids are examples. EKS Pod Identity instead of IRSA: no OIDC provider,
# and the pod receives AWS_CONTAINER_CREDENTIALS_FULL_URI (see output/06-bedrock-pod-identity.txt for that path).
set -euo pipefail
aws iam create-role --role-name spring-ai-bedrock \
--assume-role-policy-document file://deploy/pod-identity-trust-policy.json
aws iam put-role-policy --role-name spring-ai-bedrock --policy-name invoke-one-model \
--policy-document file://deploy/bedrock-invoke-policy.json
aws eks create-pod-identity-association --cluster-name my-cluster --namespace ai \
--service-account spring-ai --role-arn arn:aws:iam::111122223333:role/spring-ai-bedrock#!/usr/bin/env bash
# NOT RUN against a real subscription. Names are examples. Gives an App Service app a system-assigned managed
# identity, lets it call one Azure OpenAI resource with Entra ID, then turns key authentication off.
set -euo pipefail
RG=my-rg; APP=my-spring-ai-app; AOAI=my-openai-resource
az webapp identity assign --resource-group "$RG" --name "$APP"
PRINCIPAL_ID=$(az webapp identity show --resource-group "$RG" --name "$APP" --query principalId -o tsv)
SCOPE=$(az cognitiveservices account show --resource-group "$RG" --name "$AOAI" --query id -o tsv)
# The data-plane role. Owner and Contributor on the resource do not let a caller run inference with Entra ID.
az role assignment create --assignee-object-id "$PRINCIPAL_ID" --assignee-principal-type ServicePrincipal \
--role "Cognitive Services OpenAI User" --scope "$SCOPE"
# Entra ID authentication needs a custom subdomain on the resource (https://<name>.openai.azure.com).
# Then switch API keys off, so a leaked key stops being a way in:
az resource update --ids "$SCOPE" --set properties.disableLocalAuth=true# NOT APPLIED to a real cluster. Client id and names are examples. AKS workload identity: DefaultAzureCredential picks
# the federated token up from the environment the webhook injects. Use the azure-default profile, or the azure
# profile with a managed identity if the pod runs on a host that has one assigned.
apiVersion: v1
kind: ServiceAccount
metadata:
name: spring-ai
namespace: ai
annotations:
azure.workload.identity/client-id: 00000000-0000-0000-0000-000000000000
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: spring-ai
namespace: ai
spec:
replicas: 2
selector:
matchLabels: { app: spring-ai }
template:
metadata:
labels:
app: spring-ai
azure.workload.identity/use: "true"
spec:
serviceAccountName: spring-ai
containers:
- name: app
image: registry.example.com/spring-ai-cloud-providers:1.0.0
env:
- name: SPRING_PROFILES_ACTIVE
value: azure-default
- name: AZURE_OPENAI_ENDPOINT
value: https://my-openai-resource.openai.azure.com/openai/v1
The full chain error from output 04
The line from 04-bedrock-no-credentials.txt, unabridged. Each provider reports its own reason, which is the quickest way to see why IRSA did not engage (for example, the web identity provider says which variable is missing).
FAILED 1: SdkClientException / root cause SdkClientException: Unable to load credentials from any of the providers in the chain AwsCredentialsProviderChain(credentialsProviders=[SystemPropertyCredentialsProvider(), EnvironmentVariableCredentialsProvider(), WebIdentityTokenFileCredentialsProvider(), ProfileCredentialsProvider(profileName=default, profileFile=ProfileFile(sections=[])), ContainerCredentialsProvider(), InstanceProfileCredentialsProvider()]) : [SystemPropertyCredentialsProvider(): Unable to load credentials from system settings. Access key must be specified either via environment variable (AWS_ACCESS_KEY_ID) or system property (aws.accessKeyId)., EnvironmentVariableCredentialsProvider(): Unable to load credentials from system settings. Access key must be specified either via environment variable (AWS_ACCESS_KEY_ID) or system property (aws.accessKeyId)., WebIdentityTokenFileCredentialsProvider(): Either the environment variable AWS_WEB_IDENTITY_TOKEN_FILE or the javaproperty aws.webIdentityTokenFile must be set., ProfileCredentialsProvider(profileName=default, profileFile=ProfileFile(sections=[])): Profile file contained no credentials for profile 'default': ProfileFile(sections=[]), ContainerCredentialsProvider(): Cannot fetch credentials from container - neither AWS_CONTAINER_CREDENTIALS_FULL_URI or AWS_CONTAINER_CREDENTIALS_RELATIVE_URI environment variables are set., InstanceProfileCredentialsProvider(): IMDS credentials have been disabled by environment variable or system property.]
The local stand-in and the child-JVM harness
LocalCloud.java is one com.sun.net.httpserver.HttpServer that routes by path and body. It answers AssumeRoleWithWebIdentity and GetCallerIdentity (STS query protocol, XML), /model/*/converse (Bedrock), /pod-identity/* (container credentials), /msi/token (the App Service identity endpoint, requires the X-IDENTITY-HEADER) and */chat/completions (Azure OpenAI). It records every request, and it can issue credentials and tokens with a chosen lifetime. Nothing it returns is real: the keys, tokens and ARNs are invented.
AppProcess.java starts the real application in a child JVM and clears the inherited environment first, so the only AWS or Azure variables the child sees are the ones the test sets. The key lines:
ProcessBuilder pb = new ProcessBuilder(cmd).redirectErrorStream(true);
pb.environment().clear();
pb.environment().put("PATH", System.getenv("PATH"));
pb.environment().put("HOME", "/nonexistent-home");
pb.environment().putAll(env);The AWS SDK reads AWS_ENDPOINT_URL_STS and AWS_ENDPOINT_URL_BEDROCK_RUNTIME to redirect those services; that is how the unmodified default chain talks to the stub. On a real cluster you set none of them.
Property reference read from the jars
From META-INF/spring-configuration-metadata.json in spring-ai-autoconfigure-model-bedrock-ai-2.1.0.jar and spring-ai-autoconfigure-model-openai-2.1.0.jar.
| Property | Type | Default | Notes |
|---|---|---|---|
spring.ai.bedrock.aws.access-key / secret-key / session-token | String | none | Static credentials. If access and secret are both set they win over the chain (output 03) |
spring.ai.bedrock.aws.region | String | us-east-1 | A non-blank value means AWS_REGION is never read (output 02) |
spring.ai.bedrock.aws.profile.name | String | none | Selects a profile; with configuration-path and credentials-path for custom files. Not run |
spring.ai.bedrock.aws.timeout | Duration | 5m | Also connection-timeout 5s, socket-timeout 90s, async-read-timeout 30s |
spring.ai.openai.microsoft-foundry | Boolean | none | Forces Azure / Microsoft Foundry mode; otherwise inferred from the base URL host |
spring.ai.openai.microsoft-deployment-name / deployment-name | String | none | The Azure deployment. I set chat.options.deployment-name |
spring.ai.openai.microsoft-foundry-service-version | AzureOpenAIServiceVersion | none | Only meaningful for the legacy URL path |
spring.ai.openai.credential | com.openai.credential.Credential | none | An object, not a string: set it in code, as AzureConfig does |
spring.ai.model.audio.speech, audio.transcription, decision, embedding, image, moderation | String | openai when absent | Set to none when you only use chat (output 11) |
What I did not verify
- Anything against a real AWS or Azure endpoint: STS, Entra ID, Bedrock and Azure OpenAI accepting the requests the libraries built.
- IAM policies, trust policies, Azure RBAC assignments and
disableLocalAuth(thedeploy/files are examples). - That the model id
us.anthropic.claude-sonnet-4-5-20250929-v1:0exists for your account and region. - The EKS webhook’s exact injected variables (AWS’s page I read confirms
AWS_ROLE_ARNandAWS_WEB_IDENTITY_TOKEN_FILEonly), AKS workload identity, and the Pod Identity agent itself: the stub imitates the credentials endpoint’s response format. - CloudTrail and Azure Monitor contents, and whether the audit principal matches them.
- Streaming (
ConverseStream) and the async Bedrock client; only blockingcall()was exercised. - The default-chain path on a laptop (SSO profile,
az login), instance profiles, and workload identity federation outside the two clouds. - Why the Azure refresh count is about two identity calls per chat call when the token is under five minutes, and the exact STS lifetime threshold below which every call refreshes.
- Timing. Latency figures printed by the application (
ms=) are replaced with a placeholder because a stub on localhost says nothing about a real cloud.
No Comments yet!