AI agents are increasingly used to perform tasks that require access to external services. An agent might deploy an application, read a cloud storage file, restart a service, or retrieve information from a database.
These operations often require credentials such as API keys, database passwords, access tokens, or cloud service credentials.
Giving an agent permanent access to these secrets creates a security risk. If the agent is compromised, misconfigured, or instructed to perform an unexpected action, its credentials could be misused.
A safer approach is to provide temporary access. The agent receives only the permissions required for a specific task, uses the credentials for a limited period, and loses access when the task finishes or the access expires.
This article explains how to implement temporary cloud secret access in an ASP.NET Core application using C#, Azure Key Vault, and managed identities.
Why AI Agents Should Not Have Permanent Secret Access
Consider an AI agent responsible for deploying applications to a cloud environment.
To complete a deployment, it may need access to:
A deployment API.
A container registry.
A cloud storage account.
A configuration service.
One approach is to place all required credentials in the agent's configuration. However, this gives the agent access even when it is not performing a deployment.
There are several problems with this design:
Credentials remain available for longer than necessary.
A compromised agent can potentially access multiple services.
It becomes difficult to identify which task used a particular credential.
Rotating credentials can require changes across multiple components.
Permanent access increases the impact of prompt injection or unauthorized tool execution.
Temporary access reduces these risks by separating the agent's identity from the credentials it needs for individual operations.
Understand the Temporary Access Model
A secure implementation should have a separate component responsible for issuing and controlling access.
The agent should not directly retrieve unrestricted secrets from the cloud secret store.
Instead, use the following flow:
The agent requests permission to perform a specific operation.
The application validates the requested tool and resource.
An access service checks whether the operation is allowed.
The service retrieves or requests a short-lived credential.
The credential is provided to the authorized tool execution component.
The tool performs the operation.
Access expires or is revoked when the task is complete.
The architecture can be represented as follows:
User Request
|
v
AI Agent
|
v
Tool Execution Service
|
v
Access Policy Validation
|
v
Temporary Credential Service
|
v
Cloud Secret Store
|
v
Authorized Tool
|
v
Cloud Resource
The important distinction is that the agent does not receive unrestricted access to the secret store. A trusted application component controls credential retrieval and use.
Configure Azure Key Vault
For this example, use Azure Key Vault to store application secrets.
Create a secret in Key Vault, such as a deployment API credential.
The application should access Key Vault through a managed identity rather than storing a Key Vault password or client secret in its configuration.
A managed identity provides an application identity that Azure can authenticate without requiring developers to manage another long-lived credential.
Install the required NuGet packages:
dotnet add package Azure.Identity
dotnet add package Azure.Security.KeyVault.Secrets
Configure the Key Vault URL:
{
"KeyVault": {
"VaultUrl": "https://your-vault-name.vault.azure.net/"
}
}
The URL identifies the vault. It does not contain a secret.
Configure the application's managed identity with permission to read only the required secrets. Prefer Azure RBAC roles scoped as narrowly as the deployment model permits.
For example, the application might have permission to read a deployment API credential without having permission to manage or delete secrets.
Create a Secret Access Request
Before retrieving a secret, the application should create an access request containing the operation details.
public class SecretAccessRequest
{
public string AgentId { get; set; } = string.Empty;
public string TaskId { get; set; } = string.Empty;
public string ToolName { get; set; } = string.Empty;
public string SecretName { get; set; } = string.Empty;
public string ResourceName { get; set; } = string.Empty;
public int RequestedDurationMinutes { get; set; }
}
This request describes why the secret is needed and which resource the agent intends to access.
However, values supplied by the agent must not be trusted automatically.
For example, an agent should not be allowed to request any secret simply by changing the SecretName property. The application must validate the requested secret against an approved tool-to-secret mapping.
A policy configuration can define permitted access:
public class ToolSecretPolicy
{
public string ToolName { get; set; } = string.Empty;
public string SecretName { get; set; } = string.Empty;
public string AllowedResourcePrefix { get; set; }
= string.Empty;
public int MaximumDurationMinutes { get; set; }
}
An example policy could allow the deployment tool to access a deployment API credential for a specific environment.
The policy should be maintained by trusted application administrators, not generated dynamically by the agent.
Build a Secret Access Service
The next step is to create a service that validates the request and retrieves the approved secret.
using Azure.Security.KeyVault.Secrets;
public class TemporarySecretService
{
private readonly SecretClient _secretClient;
private readonly ILogger<TemporarySecretService> _logger;
public TemporarySecretService(
SecretClient secretClient,
ILogger<TemporarySecretService> logger)
{
_secretClient = secretClient;
_logger = logger;
}
public async Task<string> GetSecretAsync(
string secretName,
CancellationToken cancellationToken)
{
var response = await _secretClient.GetSecretAsync(
secretName,
cancellationToken: cancellationToken);
_logger.LogInformation(
"Retrieved secret {SecretName}",
secretName);
return response.Value.Value;
}
}
This service uses the Azure SDK to retrieve a secret.
The method should only be called after the application has validated the access policy. In a larger application, keep this method internal to the trusted credential-handling component rather than exposing it directly as an agent tool.
Also, do not log the returned secret. Even the secret name may reveal internal infrastructure details, so apply the organization's logging classification rules.
Register the services:
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
var builder = WebApplication.CreateBuilder(args);
var vaultUrl = builder.Configuration[
"KeyVault:VaultUrl"];
builder.Services.AddSingleton(
new SecretClient(
new Uri(vaultUrl!),
new DefaultAzureCredential()));
builder.Services.AddScoped<TemporarySecretService>();
DefaultAzureCredential supports several authentication methods. During local development, it can use an available developer identity. In an Azure-hosted environment, configure the appropriate managed identity.
Validate Access Before Retrieving Secrets
The secret service should not decide which agent can access which credential. That responsibility belongs to an authorization layer.
Create a policy validation service:
public class SecretAccessValidator
{
private readonly IReadOnlyList<ToolSecretPolicy> _policies;
public SecretAccessValidator(
IReadOnlyList<ToolSecretPolicy> policies)
{
_policies = policies;
}
public ToolSecretPolicy Validate(
SecretAccessRequest request)
{
var policy = _policies.FirstOrDefault(
x => x.ToolName == request.ToolName
&& x.SecretName == request.SecretName);
if (policy == null)
{
throw new UnauthorizedAccessException(
"The tool is not authorized to access this secret.");
}
if (!request.ResourceName.StartsWith(
policy.AllowedResourcePrefix,
StringComparison.OrdinalIgnoreCase))
{
throw new UnauthorizedAccessException(
"The requested resource is not allowed.");
}
if (request.RequestedDurationMinutes <= 0 ||
request.RequestedDurationMinutes >
policy.MaximumDurationMinutes)
{
throw new UnauthorizedAccessException(
"The requested access duration is not allowed.");
}
return policy;
}
}
This example checks the tool name, secret name, resource prefix, and requested duration.
In production, resource authorization should use canonical resource identifiers and explicit allowlists rather than relying only on string prefixes. Otherwise, similarly named resources or unexpected naming patterns may bypass the intended restriction.
The validator should also check the authenticated user, agent identity, environment, task ownership, and any required approval.
Limit How Long Credentials Remain Available
Retrieving a secret from Key Vault does not automatically make that secret temporary.
If the returned value is a permanent API key, it remains valid until the issuing system rotates or revokes it.
There are two different approaches to temporary access.
Approach 1: Use a short-lived credential
The preferred approach is to request a credential from the target service that has a defined expiration time.
For example, a cloud platform may issue a short-lived access token or temporary role credentials.
The application can then provide the credential to the authorized tool execution component.
This limits the validity of the credential even if it is accidentally exposed.
Approach 2: Use a permanent secret through a controlled proxy
Some systems only provide long-lived API keys.
In that situation, avoid returning the permanent key to the agent. Instead, keep it inside a trusted service and expose a restricted operation.
For example:
AI Agent
|
v
Deployment Tool
|
v
Credential Proxy
|
v
Deployment API
The agent requests a deployment operation, but the proxy adds the permanent credential internally.
This is not true credential expiration. It is controlled access to a permanent secret. The proxy must enforce authorization, operation restrictions, rate limits, and audit logging.
Track Access and Expiration
Every temporary access request should have an audit record.
A useful model looks like this:
public class SecretAccessAudit
{
public Guid Id { get; set; }
public string AgentId { get; set; } = string.Empty;
public string TaskId { get; set; } = string.Empty;
public string ToolName { get; set; } = string.Empty;
public string SecretName { get; set; } = string.Empty;
public DateTime GrantedAtUtc { get; set; }
public DateTime ExpiresAtUtc { get; set; }
public DateTime? RevokedAtUtc { get; set; }
public string Status { get; set; } = "Granted";
}
The audit record should capture:
Which agent requested access.
Which task required the credential.
Which tool was authorized.
When access was granted.
When access should expire.
Whether access was revoked.
Which policy approved the request.
Never store the actual secret or token in this audit table.
For compliance-sensitive applications, write audit events to a durable, access-controlled store with appropriate tamper protection. Ordinary application logs should not be treated as an immutable audit trail.
Handle Expiration and Revocation Correctly
A common mistake is assuming that clearing a variable removes access to a credential.
For example:
secret = null;
This only removes one application reference. It does not invalidate the credential at the target service.
True revocation depends on the credential type and the issuing system.
For a short-lived token, the token issuer should enforce its expiration. If supported, the application can also request explicit revocation.
For temporary cloud role credentials, the cloud provider controls their validity period. Removing the credentials from application memory does not necessarily invalidate credentials that have already been issued.
For a permanent API key, the issuing service must revoke or rotate the key to make it unusable.
A secure implementation should therefore:
Set the shortest practical credential lifetime.
Avoid caching credentials beyond their required lifetime.
Stop issuing credentials when the task is cancelled.
Revoke credentials when the provider supports revocation.
Monitor access after the associated task finishes.
Use a recovery process for tasks that terminate unexpectedly.
Common Mistakes to Avoid
One common mistake is giving the agent direct access to Key Vault. This allows the agent to request secrets outside the intended workflow.
Another mistake is assuming that a five-minute application timeout makes a permanent API key expire after five minutes. The application timeout does not change the credential's validity at the provider.
Developers also sometimes use the same cloud identity for every tool. This makes it difficult to restrict permissions and investigate unexpected access.
Avoid passing secrets through prompts, conversation history, model context, or tool descriptions. Credentials should remain within trusted application components.
Finally, do not rely only on successful execution logs. Record denied requests, expired access attempts, and failed authorization checks as well.
Summary
AI agents should not have unrestricted access to cloud secrets.
A safer design uses a trusted application service to validate each request, retrieve approved credentials, and control how they are used.
Azure Key Vault and managed identities provide a useful foundation for protecting stored secrets. Short-lived credentials offer stronger protection when the target service supports them. When only permanent API keys are available, a restricted credential proxy can prevent the agent from accessing the keys directly.
The most important point is to separate agent permissions from credential management. The agent should request an operation, while the application decides whether that operation is allowed and provides only the access required to complete it.
Join the conversation! Your thoughts help the community grow.