Security Guide

AI Agent Credential Security: API Keys, OAuth Tokens and Secrets

Store them safely, scope them tightly, expire them, and verify authorization outside the model.

The short answer. Keep secrets out of prompts and logs, give every agent its own narrowly scoped identity, make credentials short-lived where the service allows, and check authorization in the tool or API, not in the model. Then test it, because a refusal from the model is not proof the credential can't be misused.

What credentials do AI agents use?

An agent rarely works alone. It talks to identity providers, APIs, databases, cloud services and third-party tools, and each link uses a credential. They are not interchangeable.

Credential What it does Typical weakness First control
API key Identifies an app or authorizes calls to a service Hardcoded, shared across environments, over-permissioned, never retired Secrets manager, one key per agent and environment
OAuth access token Grants defined access to a resource Scope too wide, audience not enforced, long lifetime Narrow scopes, audience restriction, short expiry
Refresh token Obtains new access tokens Stolen copy keeps working after the access token expires Rotation or sender-constraint, tested revocation
Service account / workload identity Lets a background agent authenticate as a machine Broad admin rights "to make it work" Task-sized permissions, short-lived credentials
Tool-held secret An integration holds the key and uses it for the agent Tool is powerful and does not check who is asking Narrow tool interface, server-side authorization

An API key is not harmless configuration just because it isn't a password. Depending on the service, holding it can mean real access to data or operations.

For OAuth, the IETF's security best current practice (RFC 9700) says access tokens should be restricted to the minimum privileges needed and audience-restricted to a specific resource server. It also says refresh tokens for public clients must be sender-constrained or use rotation. Those are good baselines for agent integrations too.

Two cautions. Short-lived credentials reduce dependence on static secrets, but they do not stop an authorized agent from misusing the access it has. And protecting a secret and restricting what the secret enables are separate requirements. This guide covers the lifecycle. For the argument that hiding a key is not the same as making it unusable, read AI agent credentials and API-key abuse.

The main AI agent credential risks

Secrets in prompts, logs or memory

Secrets leak through more than source code. They show up in debug output, exception messages, traces, chat histories, tool responses and agent memory. A developer pastes a key into a prompt while troubleshooting. A tool returns configuration and the agent repeats it later.

Controls: keep credentials out of model context unless strictly necessary, redact secrets from logs and traces, restrict who can read conversation histories, set retention limits, and test whether secrets can be extracted through ordinary requests, adversarial prompts and tool output.

Prompt injection that leads to credential misuse

Hostile text in a web page, file, email or ticket can ask the agent to read configuration or send data out. Whether that works depends on what the agent can access, which tools it can call and whether anything independent blocks the action.

In a typical failure the model is not the only thing that broke. A tool returned a secret it should not have, and a second tool could send data out with no authorization check. That is a credential-isolation and tool-authorization problem. See what prompt injection is.

Controls: secrets outside model context, retrieval permissions separate from outbound-communication permissions, independent validation of sensitive actions, and tests that run malicious content through the whole workflow.

Overprivileged tokens and service accounts

A reporting agent needs read access to sales figures but runs on a shared service account that can edit customer records. A bug or a manipulated step now has consequences far beyond reporting. OWASP lists excessive permissions as a root cause of Excessive Agency (LLM06:2025).

Controls: least privilege per agent identity, separate read, write, admin and financial rights, distinct identities per agent and environment, extra authorization for sensitive actions, and a review of effective permissions, not documented intentions. See AI agent permissions and non-human identity management.

Long-lived credentials and partial revocation

Static keys and long-lived refresh tokens stay useful to an attacker after an incident starts. Teams often disable the agent's interface while the credential stays live, or rotate a secret in one service while copies sit in others.

Controls: short-lived credentials where practical, documented rotation and revocation steps, a list of every system that consumes each credential, revocation of active sessions and refresh tokens, and a check that the old credential really stops working.

Shared credentials across agents and environments

A test agent holding a production secret is a route into live systems. When several agents share one identity, you cannot tell which one acted.

Controls: separate dev, staging and production credentials, one identity per agent or narrow workload, no production secrets in test fixtures, a named owner for every credential, and logs that record the agent and operation behind each sensitive action.

Powerful tools that hold the key

The integration may keep the secret safe but expose a tool that takes any URL, account ID or operation name. The model never sees the secret and still misuses the authority behind it.

Controls: narrow tool interfaces with explicit allowed operations, server-side argument validation, authorization bound to the user, agent, resource and action, and restricted outbound network access. See AI agent tool security: MCP and function calling.

How to secure AI agent API keys, OAuth tokens and secrets

  1. Store secrets outside prompts and source code. Use a secrets manager or protected runtime configuration. Keep them out of repositories, system prompts, sample conversations, client-side code and unrestricted logs. The model should not see a secret just because the application needs it.
  2. Apply least privilege to every credential. Review OAuth scopes, audience and lifetime, the operations each API key allows, and the effective permissions of each service account. Verify it in practice: inherited roles and broad endpoints can allow actions the configuration appears to forbid.
  3. Separate identities and environments. One identity per agent where practical. It limits blast radius and answers the investigation questions: which agent, which identity, what authority.
  4. Set lifetimes, rotation and revocation. Not every API key supports expiry and not every OAuth provider supports the same rotation features, so write the policy per credential type and test emergency revocation. Rotation is incomplete if old credentials are still accepted downstream.
  5. Enforce authorization outside the model. A prompt saying "never access customer records without permission" is not a security boundary. The API or tool service should check whether the authenticated identity may perform this operation on this resource.
  6. Validate tool requests and control data movement. Validate arguments, resource IDs and destination URLs. A tool that can read confidential data should not automatically be able to send it anywhere.
  7. Monitor credential use. Log identity, token identifier where appropriate, operation, resource, authorization decision and outcome, never the raw secret. Alert on unexpected privilege use, unusual volume and repeated authorization failures.

What should you test?

Credential testing should follow the whole path from agent input to the final action, in an authorized test environment.

Scenario What to verify
Secret exposure Can the agent reveal credentials through prompts, tool output, errors or logs?
Prompt injection Can untrusted content trigger an unauthorized tool action?
Excessive permissions Can a read-only agent perform write or admin operations?
Scope enforcement Does the target service reject out-of-scope operations?
Cross-agent access Can one agent use another agent's identity or resources?
Environment separation Can a test agent reach production credentials or data?
Expiry and revocation Do expired or revoked credentials stop working?
Tool argument manipulation Can altered parameters bypass resource or operation limits?
Data exfiltration Can retrieved data be sent to an unauthorized destination?
Auditability Can investigators identify agent, identity, operation and outcome?

Do not assume every suspicious reply is a successful attack. Confirm the target service accepted the request and the protected data was reachable. And do not treat a refusal as proof of safety: the API and tool controls must hold even when the model produces an unsafe request. More attack paths are in AI API attack vectors and AI API security.

Pre-deployment checklist

This is a starting point, not a substitute for a risk assessment. Agents that handle money, regulated data or privileged infrastructure need stronger controls and independent approvals.

How is credential security different from transaction security?

Credential security decides who or what can authenticate and what it can reach. Transaction security decides whether a particular action is allowed under the business rules, limits and approvals. A purchasing agent can hold a securely stored, correctly scoped token and still submit an order without checking the approved supplier, the spending limit or whether a person had to sign off. Use the AI agent transaction security checklist for that layer, and the token security overview for how the pieces fit.

Where does HexTyx fit?

HexTyx tests behaviour: can an agent be manipulated into using access it already has? The scanner runs 33 attack modules, including indirect prompt injection and agentic tool abuse against tool-using agents, and Aegis checks tool calls at runtime. It does not audit secret storage, identity-provider configuration or rotation. Those need a direct configuration review, and the findings depend on your architecture and scope. Start with the free playground or the AI Agent Security Exposure Assessment.

Frequently Asked Questions

What is AI agent credential security?
It is the protection of the API keys, OAuth tokens, service-account credentials and other secrets AI agents use. It includes secure storage, least privilege, lifecycle management, authorization enforcement, monitoring and testing.
How should API keys be protected in AI agents?
Store them in a secrets manager or protected runtime configuration, keep them out of prompts and logs, restrict their permissions, use separate keys per agent and environment, and set rotation and revocation procedures.
Are OAuth tokens safer than API keys for AI agents?
Neither is safer in every case. OAuth can offer scopes, audiences and short-lived access tokens when implemented well. API keys may be the only option for some services. Choose based on what the service supports, your threat model and the credential's lifecycle.
Can prompt injection steal AI agent credentials?
It can contribute when an agent or connected tool can reach sensitive information and other controls fail to stop disclosure. It does not automatically defeat secret storage or authentication. Keep secrets away from the model and enforce authorization outside it.
Why are refresh tokens especially sensitive?
They let a client obtain new access tokens, which can extend an attacker's access beyond the life of one access token. Restrict who can read them and use the rotation, sender-constraint, expiry and revocation features your provider supports.
What is the difference between credential security and transaction security?
Credential security controls who or what can authenticate and access a service. Transaction security checks whether a specific action is allowed under business rules, limits and approvals. An agent that can take consequential actions needs both.
How can organizations test AI agent credential security?
Run an authorized assessment covering secret exposure, scope enforcement, excessive permissions, prompt-injection paths, tool authorization, revocation and unauthorized data movement. Verify what the connected services actually accepted instead of relying on the model's replies.

Sources

Is your AI a chatbot or an agent?

Run the free playground scanner against your AI application and see what an attacker could make it do.

Related Guides

Best Practices
AI Agent Token Security
Best Practices
AI Agent Credentials and API-Key Abuse
Best Practices
AI Agent Permissions
Attack Vectors
AI API Security
All Topics
AI Security Topic Hub →