

# Provide identity and credential management for agent applications with Amazon Bedrock AgentCore Identity
<a name="identity"></a>

Amazon Bedrock AgentCore Identity is an identity and credential management service designed specifically for AI agents and automated workloads. It provides secure authentication, authorization, and credential management capabilities that enable agents and tools to access AWS resources and third-party services on behalf of users while helping to maintain strict security controls and audit trails. Agent identities are implemented as workload identities with specialized attributes that enable agent-specific capabilities while helping to maintain compatibility with industry-standard workload identity patterns. The service integrates natively with Amazon Bedrock AgentCore to provide identity and credential management for agent applications, including [Host agent or tools with Amazon Bedrock AgentCore Runtime](agents-tools-runtime.md) and [Amazon Bedrock AgentCore Gateway: Securely connect tools and other resources to your Gateway](gateway.md).

**Topics**
+ [

# Overview of Amazon Bedrock AgentCore Identity
](identity-overview.md)
+ [

# Get started with AgentCore Identity
](identity-getting-started.md)
+ [

# Using the AgentCore Identity console
](identity-how-to.md)
+ [

# Manage workload identities with AgentCore Identity
](identity-manage-agent-ids.md)
+ [

# Configure inbound JWT authorizer
](inbound-jwt-authorizer.md)
+ [

# Manage credential providers with AgentCore Identity
](identity-outbound-credential-provider.md)
+ [

# Provider setup and configuration
](identity-idps.md)
+ [

# Data protection in Amazon Bedrock AgentCore Identity
](identity-data-protection.md)
+ [

# Tagging AgentCore Identity resources
](identity-tagging.md)

# Overview of Amazon Bedrock AgentCore Identity
<a name="identity-overview"></a>

In the rapidly evolving landscape of AI agents, organizations need robust identity management solutions that can handle the unique challenges associated with non-human identities. Amazon Bedrock AgentCore Identity addresses these challenges by providing a centralized capability for managing agent identities, securing credentials, and enabling seamless integration with AWS and third-party services through Sigv4, standardized OAuth 2.0 flows, and API keys.

The service implements authentication and authorization controls that verify each request independently, requiring explicit verification for all access attempts regardless of source. It integrates seamlessly with AWS services while also enabling agents to securely access external tools and services. Whether you’re building simple automation scripts or complex multi-agent systems, AgentCore Identity provides the identity foundation to help your applications operate securely and efficiently.

**Topics**
+ [

# Features of AgentCore Identity
](key-features-and-benefits.md)
+ [

# AgentCore Identity terminology
](identity-terminology.md)
+ [

# Example use cases
](identity-use-cases.md)

# Features of AgentCore Identity
<a name="key-features-and-benefits"></a>

AgentCore Identity offers a set of features designed to address the unique challenges of workload identity management and credential security:

**Topics**
+ [

## Centralized agent identity management
](#centralized-agent-identity-management)
+ [

## Secure credential storage
](#secure-credential-storage)
+ [

## OAuth 2.0 flow support
](#oauth2-flow-support)
+ [

## Agent identity and access controls
](#token-exchange-and-delegation)
+ [

## AgentCore SDK Integration
](#bedrock-agentcore-integration)
+ [

## Request verification security
](#request-verification-security)

## Centralized agent identity management
<a name="centralized-agent-identity-management"></a>

Create, manage, and organize agent and workload identities through a unified directory service that acts as the single source of truth for all agent identities within your organization. Each agent receives a unique identity with associated metadata (such as name, ARN, OAuth return URLs, created time, last updated time) that can be managed centrally across your organization. The agent identity directory functions similarly to [Cognito User Pools](https://docs.aws.amazon.com/cognito/latest/developerguide/what-is-amazon-cognito.html#what-is-amazon-cognito-user-pools) , providing a unit of governance that allows administrators to configure policies across a common set of agent identities. Agent identities are managed as specialized workload identities with agent-specific attributes and capabilities. For detailed procedures on creating and managing agent identities, see [Manage workload identities with AgentCore Identity](identity-manage-agent-ids.md).

The centralized approach eliminates the complexity of managing agent identities across different environments and systems. Whether your agents run on AgentCore Runtime, self-hosted environments, or hybrid deployments, the service provides consistent identity management regardless of where your agents are deployed. Each agent identity receives a unique ARN (such as `arn:aws:bedrock-agentcore:region:account:workload-identity/directory/default/workload-identity/agent-name`) that enables precise access control and resource management. This centralization also enables hierarchical organization and group-based access controls, making it easier to implement enterprise-wide governance policies and maintain compliance across all agent operations. The hierarchical structure in the ARN path (with directory/default/workload-identity/agent-name components) allows administrators to organize agents logically and apply policies at different levels of the hierarchy—for example, targeting all agents within a specific directory or with similar attributes—without having to manage each agent identity individually.

## Secure credential storage
<a name="secure-credential-storage"></a>

The token vault provides security for storing OAuth 2.0 tokens, OAuth client credentials, and API keys with comprehensive encryption at rest and in transit. All credentials are encrypted using either customer-managed or service-managed AWS KMS keys and access-controlled to prevent unauthorized retrieval. The vault implements strict access controls, ensuring that credentials can only be accessed by authorized agents for specific purposes and only when they present verifiable proof of workload identity.

Building on OAuth 2.0’s scope-based security model, the token vault implements additional security measures where every access request is validated independently, even from callers within the same trust domain. This extra security mechanism is necessary to protect end-user data from malicious or misbehaving agent code. The vault securely stores OAuth 2.0 tokens, reducing security risks while improving your overall security posture.

## OAuth 2.0 flow support
<a name="oauth2-flow-support"></a>

Native support for both OAuth 2.0 client credentials grant (machine-to-machine) and OAuth 2.0 authorization code grant (user-delegated access) flows enables comprehensive authentication patterns for different use cases. The service handles the complexity of OAuth 2.0 implementations while providing simple APIs for agents to access AWS resources and third-party services. For 2LO flows, agents can authenticate themselves directly with resource servers without user interaction, while 3LO flows enable explicit user consent and authorization for accessing user-specific data from external services.

The service also provides built-in OAuth 2.0 credential providers for popular services such as Google, GitHub, Slack, Salesforce, and Atlassian (Jira), with authorization server endpoints and provider-specific parameters pre-filled to reduce development effort. For custom integrations, the service supports configurable OAuth 2.0 credential providers that can be tailored to work with any OAuth 2.0-compatible resource server. This comprehensive OAuth 2.0 support eliminates the heavy-lifting of agent developers implementing complex authorization flows and reduces the risk of security vulnerabilities in custom implementations. For comprehensive information about configuring these providers, see [Configure credential provider](resource-providers.md).

## Agent identity and access controls
<a name="token-exchange-and-delegation"></a>

AgentCore Identity supports impersonation flow where agents can access resources using credentials provided to them. This approach enables agents to perform actions on behalf of users while maintaining audit trails and access controls. The impersonation process allows agents to use provided credentials to access resources, with authorization decisions based on those credentials.

## AgentCore SDK Integration
<a name="bedrock-agentcore-integration"></a>

Seamless integration with the AgentCore SDK through declarative annotations like @requires\$1access\$1token and @requires\$1api\$1key automatically handles credential retrieval and injection, reducing boilerplate code and potential security vulnerabilities. These annotations eliminate the need for developers to implement complex OAuth flows manually, instead providing a simple declarative interface that abstracts away the underlying complexity of token management and credential handling.

The SDK integration also provides automatic error handling for common scenarios such as token expiration and user consent requirements. When tokens expire or user consent is needed, the SDK automatically generates appropriate authorization URLs and handles the OAuth flow orchestration, presenting developers with simple success or failure responses. This integration significantly reduces development time and the likelihood of security vulnerabilities while ensuring that all credential operations follow security best practices.

## Request verification security
<a name="request-verification-security"></a>

The service implements validation of all requests, including token signature verification, expiration checks, and scope validation.

By treating every request as requiring verification and requiring explicit proof of authorization, the service implements security validation for each request. All operations are logged with detailed context for security monitoring and compliance reporting, providing visibility into agent activities.

These features combine to provide significant benefits for organizations deploying AI agents:
+  **Reduced Security Risk** : Centralized credential management eliminates the need to embed secrets in agent code or configuration files.
+  **Simplified Development** : Declarative APIs and SDK integration reduce the complexity of implementing secure authentication in agent applications.
+  **Enhanced Compliance** : Comprehensive audit trails and access controls support regulatory compliance requirements.
+  **Operational Efficiency** : Automated credential refresh reduces operational overhead while improving security posture.

# AgentCore Identity terminology
<a name="identity-terminology"></a>

AgentCore Identity uses specific terminology to describe the components, processes, and relationships involved in workload identity management and credential handling. Understanding these terms will help you better comprehend how the service orchestrates secure authentication and authorization across multiple parties in agent workflows.


| Term | Definition | 
| --- | --- | 
|   **Identity and Authentication**   |  Agent  | 
|  An AI-powered application or automated workload that performs tasks on behalf of users by accessing AWS resources and third-party services. Agents act with pre-authorized user consent, to accomplish user goals, such as retrieving data from APIs, processing information, or integrating with third-party systems. Unlike traditional applications that run with static credentials, agents require dynamic identity management to securely access resources across multiple trust domains while maintaining proper authentication and authorization boundaries.  |  Agent identity  | 
|  A unique identifier and associated metadata for an AI agent or automated workload. Agent identities are implemented as workload identities with specific attributes that identify them as agents, enabling specialized agent capabilities while maintaining compatibility with broader workload identity standards. Agent identities enable agents to authenticate as themselves rather than impersonating users, supporting delegation-based access patterns.  |  Agent identity directory  | 
|  A centralized registry that manages agent identities and their associated metadata and access policies. Similar to Cognito User Pools, it acts as a unit of governance for organizing agent identities within an account or region.  |  Workload identity  | 
|  The underlying technical implementation for agent identities, representing a logical application or workload that is independent of specific hardware or infrastructure. Workload identities can operate across different environments while maintaining consistent authentication. Agent identities are a specialized type of workload identity with additional agent-specific attributes and capabilities.  |   **Integration and Protocols**   | 
|  Cross-service agents  |  AI agents that perform actions across multiple services, which may include accessing system resources (using machine-to-machine authentication) or user-specific data (using user-delegated access). Examples include agents that integrate with multiple backend systems for data processing or agents that access a user’s calendar, email, and document storage. These agents require sophisticated identity management to operate securely across different trust domains.  | 
|  MCP client  |  A client component that allows agents to communicate with MCP servers to access external tools and resources. MCP clients present authentication tokens to access MCP tools securely.  | 
|  MCP server  |  An intermediate server that hosts tools and resources for MCP clients. MCP servers act as OAuth 2.0 resource servers when accessed by agents and as OAuth 2.0 clients when accessing downstream resources.  | 
|  Model context protocol (MCP)  |  MCP is an open protocol that standardizes how applications provide context to language models. AgentCore Identity is MCP-compliant, supporting standard protocols for agent-to-tool communication and enabling secure integration with MCP servers and tools.  | 
|   **OAuth and Token Management**   |  OAuth 2.0  | 
|  An industry-standard authorization framework (defined in [RFC 6749](https://datatracker.ietf.org/doc/html/rfc6749) ) that enables applications to obtain limited access to user accounts on external services without exposing user credentials. OAuth 2.0 provides secure delegation by allowing users to grant third-party applications access to their resources through access tokens rather than sharing passwords. For agent applications, OAuth 2.0 enables secure access to user data across multiple services while maintaining proper authentication boundaries and user consent mechanisms.  |  OAuth 2.0 authorizer  | 
|  An SDK component that authenticates and authorizes incoming OAuth 2.0 API requests to agent endpoints. It validates tokens before allowing access to agent services.  |  OAuth 2.0 client credentials grant (2LO)  | 
|  OAuth client credentials grant used for machine-to-machine authentication where no user interaction is required. Agents use 2LO to authenticate themselves directly with resource servers.  |  OAuth 2.0 authorization code grant (3LO)  | 
|  OAuth authorization code grant that involves user consent and interaction. Agents use 3LO when they need explicit user permission to access user-specific data from external services like Google Calendar or Salesforce.  |  Agent access token  | 
|  An AWS-signed token that contains both workload identity and user identity information, enabling downstream services to make authorization decisions based on both identities. These tokens are created through the token exchange process.  |   **Security and Trust**   | 
|  Identity propagation  |  The process of maintaining and passing identity context through a chain of service calls. This enables downstream services to make authorization decisions based on both the calling service identity and the original user identity.  | 
|  Trust domain  |  A security boundary within which entities share common authentication and authorization mechanisms. Agent workflows often span multiple trust domains, requiring careful identity propagation and token exchange.  | 
|  Request verification security  |  A security model where every request is authenticated and authorized regardless of source or previous trust relationships. AgentCore Identity implements request verification to ensure validation of all access requests.  | 
|   **Service Components**   |  Resource credential provider  | 
|  A component that manages connections to external identity providers and resource servers, handling OAuth 2.0 authorization flows and credential retrieval. It orchestrates the complex process of obtaining and refreshing credentials from third-party services. For detailed configuration information, see [Configure credential provider](resource-providers.md).  |  Token vault  | 

# Example use cases
<a name="identity-use-cases"></a>

Amazon Bedrock AgentCore Identity supports a wide range of use cases across different industries and application types. This section provides detailed examples of how the service can be applied in specific scenarios, demonstrating both user-delegated access (OAuth 2.0 authorization code grant) and machine-to-machine authentication (OAuth 2.0 client credentials grant) patterns.

**Topics**
+ [

## Personal assistant agents
](#personal-assistant-agents)
+ [

## Enterprise automation agents
](#enterprise-automation-agents)
+ [

## Customer service agents
](#customer-service-agents)
+ [

## Data processing and analytics agents
](#data-processing-and-analytics-agents)
+ [

## Development and DevOps agents
](#development-and-devops-agents)

## Personal assistant agents
<a name="personal-assistant-agents"></a>

AI agents that help users manage their personal productivity by accessing services like Google Drive, Microsoft Office 365, or Slack represent one of the most common and valuable applications of AgentCore Identity. These agents use OAuth 2.0 authorization code grant to obtain explicit user consent (3Lo) and access user data securely across multiple systems. For example, a research agent might search the web using AgentCore Browser, generate a comprehensive report, and save it to the user’s Google Drive, all while maintaining proper authentication and authorization throughout the entire workflow.

The complexity of managing credentials across multiple third-party services makes AgentCore Identity particularly valuable for personal assistant scenarios. Consider a meeting agent that needs to access a user’s Google Calendar to check availability, join a Zoom meeting to take notes, schedule follow-up meetings, and draft emails for approval. Each of these services requires different authentication mechanisms and user consent, but AgentCore Identity orchestrates the entire process seamlessly while the agent maintains its own identity and the user retains control over what data is accessed.

Personal assistant agents also benefit from AgentCore Identity’s token storage and secure credential management, which eliminate the need for users to repeatedly authorize access to their accounts. Once a user has granted permission for an agent to access their Google Drive, for instance, the agent can continue to access that service for subsequent tasks without requiring re-authorization, as long as the stored tokens remain valid. This creates a smooth user experience while maintaining security through proper token management.

## Enterprise automation agents
<a name="enterprise-automation-agents"></a>

Agents that automate business processes by integrating with enterprise systems like Salesforce, SharePoint, or internal APIs represent a critical use case for organizations seeking to improve operational efficiency. These agents typically use OAuth 2.0 client credentials grant for machine-to-machine authentication (2Lo) when accessing systems that don’t require user interaction, and may require access to multiple systems with different authentication requirements. For example, an HR automation agent might need to access employee data from an HRIS system, update records in Salesforce, and generate reports in SharePoint, each requiring different credentials and authorization scopes.

Enterprise automation scenarios often involve complex workflows that span multiple trust domains and require careful identity propagation to maintain security and compliance. AgentCore Identity addresses this challenge by providing a centralized approach to credential management that works across different enterprise systems. The service supports both AWS-hosted resources with IAM-based authentication and external enterprise systems with OAuth 2.0 or API key authentication, enabling agents to operate seamlessly across hybrid environments while helping to maintain consistent security standards.

The audit and compliance capabilities of AgentCore Identity are particularly important for enterprise automation use cases, where organizations need to maintain detailed records of automated actions for regulatory compliance and security monitoring. Every action performed by an enterprise automation agent is logged with both the agent identity and any associated user context, providing complete traceability of automated business processes. This level of visibility helps with compliance requirements and enables organizations to quickly identify and respond to any unauthorized or unexpected agent behavior.

## Customer service agents
<a name="customer-service-agents"></a>

AI agents that assist customer service representatives by accessing customer data from CRM systems, knowledge bases, and support ticketing systems must authenticate securely while providing real-time assistance during customer interactions. These agents need to access sensitive customer information from multiple sources while maintaining strict security controls and audit trails. For example, a customer service agent might need to access a customer’s order history from an e-commerce platform, check their support ticket status in a ticketing system, and retrieve relevant troubleshooting information from a knowledge base, all while the customer is on the phone.

The real-time nature of customer service interactions makes credential management particularly challenging, as agents cannot afford delays caused by authentication failures or expired tokens. AgentCore Identity addresses this challenge through its comprehensive error handling, ensuring that customer service agents can access the information they need without interruption. The service also supports fine-grained access controls that can be configured to have agents only access customer data that is relevant to the specific interaction, supporting privacy requirements and regulatory compliance.

## Data processing and analytics agents
<a name="data-processing-and-analytics-agents"></a>

Agents that collect, process, and analyze data from multiple sources, including cloud storage services, databases, and APIs, often require long-running access to data sources. These agents typically operate on scheduled or triggered workflows that may run for hours or days, accessing large datasets from various sources to perform complex analytics operations. For example, a financial analytics agent might collect transaction data from multiple payment processors, combine it with customer data from CRM systems, and generate comprehensive reports that are stored in data warehouses and shared with business stakeholders.

The long-running nature of data processing workflows makes credential management particularly complex, as tokens may expire during processing and agents need to handle authentication failures gracefully without losing progress on lengthy operations. AgentCore Identity addresses these challenges through its robust error handling, helping data processing agents maintain access to required resources throughout their entire execution lifecycle. The service also supports batch processing scenarios where agents need to access multiple data sources simultaneously, providing efficient credential management that scales with the complexity of the data processing workflow.

Data processing and analytics use cases also benefit from AgentCore Identity’s support for different authentication mechanisms across various data sources. A single analytics workflow might need to access data from AWS services using IAM credentials, third-party APIs using OAuth 2.0 tokens, and on-premise databases using API keys or other authentication methods. AgentCore Identity provides a unified interface for managing all these different credential types, enabling data processing agents to focus on their core analytics functions rather than the complexity of credential management across diverse systems.

## Development and DevOps agents
<a name="development-and-devops-agents"></a>

Agents that automate software development workflows by integrating with version control systems, CI/CD pipelines, and deployment systems require secure access to development tools and infrastructure while maintaining comprehensive audit trails for compliance purposes. These agents might automatically create pull requests, trigger builds, deploy applications, and update documentation across multiple development tools and systems. For example, a DevOps agent might monitor application performance, detect issues, automatically create bug reports in JIRA, generate fixes through code analysis, and deploy patches through CI/CD pipelines, all while maintaining proper authentication and authorization throughout the entire workflow.

Development and DevOps scenarios present unique security challenges because agents often need elevated privileges to perform deployment and infrastructure management tasks, while also needing to maintain strict controls to prevent unauthorized changes to production systems. AgentCore Identity addresses these challenges through its fine-grained access control capabilities and comprehensive audit logging, ensuring that DevOps agents can perform necessary automation tasks while supporting security and compliance. The service supports role-based access controls that can be configured to limit agent access to specific environments, repositories, or deployment targets based on the agent’s identity and the context of the operation.

The audit and compliance capabilities of AgentCore Identity are particularly valuable for development and DevOps use cases, where organizations need to maintain detailed records of all changes to code, infrastructure, and deployment configurations. Every action performed by a DevOps agent is logged with complete context, including the agent identity, the specific resources accessed, and the changes made, providing the level of traceability that supports regulatory compliance and security auditing. This comprehensive logging also enables organizations to quickly identify the root cause of issues and roll back changes when necessary, supporting the reliability and stability of development and deployment processes.

# Get started with AgentCore Identity
<a name="identity-getting-started"></a>

If you’re building AI agents that need to access external services like Google Drive, Slack, or GitHub, Amazon Bedrock AgentCore Identity provides the secure authentication infrastructure you need. This section offers two practical getting started tutorials that demonstrate how to implement identity features in your agents. Depending on your specific business needs, you can start with a complete end-to-end agent deployment, or focus on OAuth2 integration patterns with Google Drive to understand the core authentication flows.

**Topics**
+ [

## Primary getting started tutorial
](#primary-tutorial)
+ [

## OAuth2 integration getting started tutorial
](#additional-tutorial)
+ [

## Common prerequisites
](#common-prerequisites)
+ [

# Build your first authenticated agent
](identity-getting-started-cognito.md)
+ [

# Integrate with Google Drive using OAuth2
](identity-getting-started-google.md)

## Primary getting started tutorial
<a name="primary-tutorial"></a>

Start here for a complete end-to-end walkthrough of AgentCore Identity features:

 [Build your first authenticated agent](identity-getting-started-cognito.md)   
 **Recommended starting point** for new users  
 **What you’ll build:** A complete working agent with authentication, deployed to AgentCore Runtime  
 **What you’ll learn:** Create Cognito user pools, configure credential providers, deploy agents, set up IAM policies, and test authentication flows  
 **Outcome:** Fully deployed agent that can authenticate users and obtain access tokens

## OAuth2 integration getting started tutorial
<a name="additional-tutorial"></a>

After completing the primary tutorial, explore OAuth2 patterns with external services:

 [Integrate with Google Drive using OAuth2](identity-getting-started-google.md)   
 **Focus:** OAuth2 flows and Google Drive integration  
 **What you’ll learn:** Set up OAuth2 credential providers, obtain access tokens, and integrate with Google services  
 **Best for:** Understanding OAuth2 authentication patterns with real external services

## Common prerequisites
<a name="common-prerequisites"></a>

Both tutorials require the following:
+ An AWS account with appropriate permissions
+ Basic familiarity with Python programming
+ Understanding of OAuth2 concepts (recommended)

Each tutorial includes specific setup instructions and additional prerequisites as needed.

# Build your first authenticated agent
<a name="identity-getting-started-cognito"></a>

This getting started tutorial walks you through building a complete authenticated agent from the ground up using Amazon Bedrock AgentCore Identity and will help you get started with implementing identity features in your agent applications. You’ll learn how to set up your development environment, create authentication infrastructure with Cognito, deploy your agent to AgentCore Runtime, and test the full authentication workflow.

By the end of this tutorial, you’ll have a fully deployed agent that can authenticate users through OAuth2 flows, obtain access tokens securely, and demonstrate the complete identity management lifecycle. Your agent will be running on AgentCore Runtime with proper IAM permissions, creating a test lab environment where you can demonstrate and test the integration capabilities.

**Topics**
+ [

## Prerequisites
](#identity-quick-start-prerequisites)
+ [

## Step 1: Create a Cognito user pool (Optional)
](#identity-quick-start-cognito)
+ [

## Step 2: Create a credential provider
](#identity-quick-start-credential-provider)
+ [

## Step 2.5: Add the callback URL to your OAuth 2.0 authorization server
](#identity-update-credential-provider)
+ [

## Step 3: Create a sample agent that initiates an OAuth 2.0 flow
](#identity-quick-start-agent)
+ [

## Step 4: Deploy the agent to AgentCore Runtime
](#identity-quick-start-deploy)
+ [

## Step 5: Invoke the agent
](#identity-quick-start-invoke)
+ [

## Clean up
](#identity-quick-start-cleanup)
+ [

## Security best practices
](#identity-quick-start-security)

## Prerequisites
<a name="identity-quick-start-prerequisites"></a>

Before you begin, ensure you have:
+ An AWS account with appropriate permissions
+ Python 3.10\$1 installed
+ The latest AWS CLI and `jq` installed
+ Node.js 18\$1 installed (for the AgentCore CLI)
+  AWS credentials and region configured ( `aws configure` )

This tutorial requires that you have an OAuth 2.0 authorization server. If you do not have one, Step 1 will create one for you using Amazon Cognito user pools. If you have an OAuth 2.0 authorization server with a client id, client secret, and a user configured, you may proceed to step 2. This authorization server will act as a resource credential provider, representing the authority that grants the agent an outbound OAuth 2.0 access token.

### Install the SDK and dependencies
<a name="identity-quick-start-install"></a>

Make a folder for this guide, create a Python virtual environment, and install the AgentCore SDK and the AWS Python SDK (boto3).

```
mkdir agentcore-identity-quickstart
cd agentcore-identity-quickstart
python3 -m venv .venv
source .venv/bin/activate
pip install bedrock-agentcore boto3 strands-agents pyjwt
```

Also create the `requirements.txt` file with the following content. This will be used later by the AgentCore deployment tool.

```
bedrock-agentcore
boto3
pyjwt
strands-agents
```

## Step 1: Create a Cognito user pool (Optional)
<a name="identity-quick-start-cognito"></a>

This tutorial requires an OAuth 2.0 authorization server. If you do not have one available for testing, or if you want to keep your test separate from your authorization server, this script will use your AWS credentials to set up an Amazon Cognito instance for you to use as an authorization server. The script will create:
+ A Cognito user pool
+ An OAuth 2.0 client, and client secret for that user pool
+ A test user and password in that Cognito user pool

Deleting the Cognito user pool AgentCoreIdentityQuickStartPool will delete the associated client\$1id and user as well.

You may choose to save this script as create\$1cognito.sh and execute it from your command line, or paste the script into your command line.

```
#!/bin/bash

REGION=$(aws configure get region)

# Create user pool
USER_POOL_ID=$(aws cognito-idp create-user-pool \
  --pool-name AgentCoreIdentityQuickStartPool \
  --query 'UserPool.Id' \
  --no-cli-pager \
  --output text)

# Create user pool domain
DOMAIN_NAME="agentcore-quickstart-$(LC_ALL=C tr -dc 'a-z0-9' < /dev/urandom | head -c 5)"
aws cognito-idp create-user-pool-domain \
  --domain $DOMAIN_NAME \
  --no-cli-pager \
  --user-pool-id $USER_POOL_ID > /dev/null

# Create user pool client with secret and hosted UI settings
CLIENT_RESPONSE=$(aws cognito-idp create-user-pool-client \
  --user-pool-id $USER_POOL_ID \
  --client-name AgentCoreQuickStart \
  --generate-secret \
  --allowed-o-auth-flows "code" \
  --allowed-o-auth-scopes "openid" "profile" "email" \
  --allowed-o-auth-flows-user-pool-client \
  --supported-identity-providers "COGNITO" \
  --query 'UserPoolClient.{ClientId:ClientId,ClientSecret:ClientSecret}' \
  --output json)

CLIENT_ID=$(echo $CLIENT_RESPONSE | jq -r '.ClientId')
CLIENT_SECRET=$(echo $CLIENT_RESPONSE | jq -r '.ClientSecret')

# Generate random username and password
USERNAME="AgentCoreTestUser$(printf "%04d" $((RANDOM % 10000)))"
PASSWORD="$(LC_ALL=C tr -dc 'A-Za-z0-9!@#$%^&*()_+-=[]{}|;:,.<>?' < /dev/urandom | head -c 16)$(LC_ALL=C tr -dc '0-9' < /dev/urandom | head -c 1)"

# Create user with permanent password
aws cognito-idp admin-create-user \
  --user-pool-id $USER_POOL_ID \
  --username $USERNAME \
  --output text > /dev/null

aws cognito-idp admin-set-user-password \
  --user-pool-id $USER_POOL_ID \
  --username $USERNAME \
  --password $PASSWORD \
  --output text > /dev/null \
  --permanent

# Get region

ISSUER_URL="https://cognito-idp.$REGION.amazonaws.com/$USER_POOL_ID/.well-known/openid-configuration"
HOSTED_UI_URL="https://$DOMAIN_NAME.auth.$REGION.amazoncognito.com"

# Output results
echo "User Pool ID: $USER_POOL_ID"
echo "Client ID: $CLIENT_ID"
echo "Client Secret: $CLIENT_SECRET"
echo "Issuer URL: $ISSUER_URL"
echo "Hosted UI URL: $HOSTED_UI_URL"
echo "Test User: $USERNAME"
echo "Test Password: $PASSWORD"

echo ""
echo "# Copy and paste these exports to set environment variables for later use:"
echo "export USER_POOL_ID='$USER_POOL_ID'"
echo "export CLIENT_ID='$CLIENT_ID'"
echo "export CLIENT_SECRET='$CLIENT_SECRET'"
echo "export ISSUER_URL='$ISSUER_URL'"
echo "export HOSTED_UI_URL='$HOSTED_UI_URL'"
echo "export COGNITO_USERNAME='$USERNAME'"
echo "export COGNITO_PASSWORD='$PASSWORD'"
```

## Step 2: Create a credential provider
<a name="identity-quick-start-credential-provider"></a>

Credential providers are how your agent accesses external services. Create a credential provider and configure it with an OAuth 2.0 client for your authorization server.

If you are using your own authorization server, set the environment variables `ISSUER_URL` , `CLIENT_ID` , and `CLIENT_SECRET` with their appropriate values from your authorization server. If you are using the previous script to create an authorization server for you with Cognito, copy the EXPORT statements from the output into your terminal to set the environment variables.

This credential provider will be used by your agent’s code to get access tokens to act on behalf of your user.

**Example**  

1. If you have an AgentCore CLI project, you can add the credential provider using the CLI. The CLI will create the provider during deployment.

   ```
   agentcore add credential \
     --name AgentCoreIdentityQuickStartProvider \
     --type oauth \
     --discovery-url "$ISSUER_URL" \
     --client-id "$CLIENT_ID" \
     --client-secret "$CLIENT_SECRET"
   ```

   The credential provider will be created when you run `agentcore deploy` in Step 4. Note the callback URL from the deploy output.

1. 

   ```
   #!/bin/bash
   # please note the expected ISSUER_URL format for Bedrock AgentCore is the full url, including .well-known/openid-configuration
   OAUTH2_CREDENTIAL_PROVIDER_RESPONSE=$(aws bedrock-agentcore-control create-oauth2-credential-provider \
     --name "AgentCoreIdentityQuickStartProvider" \
     --credential-provider-vendor "CustomOauth2" \
     --oauth2-provider-config-input '{
       "customOauth2ProviderConfig": {
         "oauthDiscovery": {
           "discoveryUrl": "'$ISSUER_URL'"
         },
         "clientId": "'$CLIENT_ID'",
         "clientSecret": "'$CLIENT_SECRET'"
       }
     }' \
     --output json)
   
   OAUTH2_CALLBACK_URL=$(echo $OAUTH2_CREDENTIAL_PROVIDER_RESPONSE | jq -r '.callbackUrl')
   
   echo "OAuth2 Callback URL: $OAUTH2_CALLBACK_URL"
   ```

## Step 2.5: Add the callback URL to your OAuth 2.0 authorization server
<a name="identity-update-credential-provider"></a>

To prevent unauthorized redirects, add the callback URL retrieved from [CreateOauth2CredentialProvider](https://docs.aws.amazon.com/bedrock-agentcore-control/latest/APIReference/API_CreateOauth2CredentialProvider.html) or [GetOauth2CredentialProvider](https://docs.aws.amazon.com/bedrock-agentcore-control/latest/APIReference/API_GetOauth2CredentialProvider.html) to your OAuth 2.0 authorization server.

If you are using the previous script to create an authorization server with Cognito, copy the EXPORT statements from the output into your terminal to set the environment variables and update the Cognito user pool client with the OAuth2 credential provider callback URL.

```
#!/bin/bash
aws cognito-idp update-user-pool-client \
    --user-pool-id $USER_POOL_ID \
    --client-id $CLIENT_ID \
    --client-name AgentCoreQuickStart \
    --allowed-o-auth-flows "code" \
    --allowed-o-auth-scopes "openid" "profile" "email" \
    --allowed-o-auth-flows-user-pool-client \
    --supported-identity-providers "COGNITO" \
    --callback-urls "$OAUTH2_CALLBACK_URL"
```

## Step 3: Create a sample agent that initiates an OAuth 2.0 flow
<a name="identity-quick-start-agent"></a>

In this step, we will create an agent that initiates an OAuth 2.0 authorization flow to get tokens to act on behalf of the user. For simplicity, the agent will not make actual calls to external services on behalf of a user, but will prove to us that it has obtained consent to act on behalf of our test user.

### Agent code
<a name="identity-quick-start-agent-code"></a>

Create a file named `agentcoreidentityquickstart.py` , and save this code.

```
"""
AgentCore Identity Outbound Token Agent

This agent demonstrates the USER_FEDERATION OAuth 2.0 flow.

It handles the OAuth 2.0 user consent flow and inspects the resulting OAuth 2.0 access token.
"""

from bedrock_agentcore.runtime import BedrockAgentCoreApp
from bedrock_agentcore.identity import requires_access_token
import asyncio
import jwt
import logging

app = BedrockAgentCoreApp()

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def decode_jwt(token):
    try:
        decoded = jwt.decode(token, options={"verify_signature": False})
        return decoded
    except Exception as e:
        return {"error": f"Error decoding JWT: {str(e)}"}

class StreamingQueue:
    def __init__(self):
        self.finished = False
        self.queue = asyncio.Queue()

    async def put(self, item):
        await self.queue.put(item)

    async def finish(self):
        self.finished = True
        await self.queue.put(None)

    async def stream(self):
        while True:
            item = await self.queue.get()
            if item is None and self.finished:
                break
            yield item

queue = StreamingQueue()

async def handle_auth_url(url):
    await queue.put(f"Authorization URL, please copy to your preferred browser: {url}")

@requires_access_token(
    provider_name="AgentCoreIdentityQuickStartProvider",
    scopes=["openid"],
    auth_flow="USER_FEDERATION",
    on_auth_url=handle_auth_url, # streams authorization URL to client
    force_authentication=True,
    callback_url='insert_oauth2_callback_url_for_session_binding',
)
async def introspect_with_decorator(*, access_token: str):
    """Introspect token using decorator"""
    logger.info("Inside introspect_with_decorator - decorator succeeded")
    await queue.put({
        "message": "Successfully received an access token to act on behalf of your user!",
        "token_claims": decode_jwt(access_token),
        "token_length": len(access_token),
        "token_preview": f"{access_token[:50]}...{access_token[-10:]}"
    })
    await queue.finish()

@app.entrypoint
async def agent_invocation(payload, context):
    """Handler that uses only the decorator approach"""
    logger.info("Agent invocation started")

    # Start the agent task and immediately begin streaming
    task = asyncio.create_task(introspect_with_decorator())

    # Stream items as they come in
    async for item in queue.stream():
        yield item

    # Wait for task completion
    await task

if __name__ == "__main__":
    app.run()
```

**Note**  
For a sample local callback server implementation to handle [session binding](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/oauth2-authorization-url-session-binding.html) , refer to [oauth2\$1callback\$1server.py](https://github.com/awslabs/amazon-bedrock-agentcore-samples/blob/main/01-tutorials/03-AgentCore-identity/05-Outbound_Auth_3lo/oauth2_callback_server.py) 

## Step 4: Deploy the agent to AgentCore Runtime
<a name="identity-quick-start-deploy"></a>

We will host this agent on AgentCore Runtime. We can do this easily with the AgentCore CLI.

From your terminal, install the AgentCore CLI and create a new project:

```
npm install -g @aws/agentcore
agentcore create --name IdentityQuickstart --defaults
```

Copy your agent script into the project’s agent directory, replacing the default agent:

```
cp agentcoreidentityquickstart.py IdentityQuickstart/app/IdentityQuickstart/main.py
```

Also copy your requirements file into the agent directory to ensure all dependencies are included in the deployment:

```
cp requirements.txt IdentityQuickstart/app/IdentityQuickstart/
```

Then deploy your project:

```
cd IdentityQuickstart
agentcore deploy
```

The CLI synthesizes a AWS CDK stack and deploys your agent to AgentCore Runtime. This takes approximately 2–3 minutes.

### Update the IAM policy of the agent to be able to access the token vault, and client secret
<a name="identity-quick-start-iam-policy"></a>

The AgentCore CLI creates the agent’s execution role during deployment, but the role does not automatically include permissions for token vault access. You need to attach an additional policy to allow the agent to retrieve OAuth 2.0 tokens at runtime.

This script retrieves your account and region from the AWS CLI, finds the agent’s execution role from the CloudFormation stack, and attaches the appropriate policy. You can copy and paste this script, or save it to a file and execute it.

```
#!/bin/bash

# Get account and region from AWS CLI
AWS_ACCOUNT=$(aws sts get-caller-identity --query Account --output text)
REGION=$(aws configure get region)

# Get execution role from CloudFormation stack outputs
EXECUTION_ROLE=$(aws cloudformation describe-stack-resources \
  --stack-name AgentCore-IdentityQuickstart-prod \
  --query "StackResources[?ResourceType=='AWS::IAM::Role'].PhysicalResourceId" \
  --output text | head -1)

echo "Parsed values:"
echo "Execution Role: $EXECUTION_ROLE"
echo "Account: $AWS_ACCOUNT"
echo "Region: $REGION"

# Create the policy document with proper variable substitution
cat > agentcore-identity-policy.json << EOF
{
"Version": "2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "AccessTokenVault",
      "Effect": "Allow",
      "Action": [
        "bedrock-agentcore:GetResourceOauth2Token",
        "secretsmanager:GetSecretValue"
      ],
      "Resource": ["arn:aws:bedrock-agentcore:$REGION:$AWS_ACCOUNT:workload-identity-directory/default/workload-identity/*",
        "arn:aws:bedrock-agentcore:$REGION:$AWS_ACCOUNT:token-vault/default/oauth2credentialprovider/AgentCoreIdentityQuickStartProvider",
        "arn:aws:bedrock-agentcore:$REGION:$AWS_ACCOUNT:workload-identity-directory/default",
        "arn:aws:bedrock-agentcore:$REGION:$AWS_ACCOUNT:token-vault/default",
        "arn:aws:secretsmanager:$REGION:$AWS_ACCOUNT:secret:bedrock-agentcore-identity!default/oauth2/AgentCoreIdentityQuickStartProvider*"
      ]
    }
  ]
}
EOF

# Create the policy
POLICY_ARN=$(aws iam create-policy \
    --policy-name AgentCoreIdentityQuickStartPolicy$(LC_ALL=C tr -dc '0-9' < /dev/urandom | head -c 4) \
    --policy-document file://agentcore-identity-policy.json \
    --query 'Policy.Arn' \
    --output text)

# Extract role name from ARN and attach policy
ROLE_NAME=$(echo $EXECUTION_ROLE | awk -F'/' '{print $NF}')
aws iam attach-role-policy \
    --role-name $ROLE_NAME \
    --policy-arn $POLICY_ARN

echo "Policy created and attached: $POLICY_ARN"

# Cleanup
rm agentcore-identity-policy.json
```

## Step 5: Invoke the agent
<a name="identity-quick-start-invoke"></a>

Now that this is all set up, you can invoke the agent. For this demo, we will use the `agentcore invoke` command and our IAM credentials. We will need to pass the `--user-id` and `--session-id` arguments when using IAM authentication.

```
agentcore invoke "TestPayload" --runtime IdentityQuickstart --user-id "SampleUserID" --session-id "ALongThirtyThreeCharacterMinimumSessionIdYouCanChangeThisAsYouNeed"
```

The agent will then return a URL to your `agentcore invoke` command. Copy and paste that URL into your preferred browser, and you will then be redirected to your authorization server’s login page. The `--user-id` parameter is the user ID you are presenting to AgentCore Identity. The `--session-id` parameter is the session ID, which must be at least 33 characters long.

Enter the username and password for your user on your authorization server when prompted on your browser, or use your preferred authentication method you have configured. If you used the script from Step 1 to create a Cognito instance, you can retrieve this from your terminal history.

Your browser should redirect to your configured OAuth2 callback URL, which handles the [session binding flow](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/oauth2-authorization-url-session-binding.html) . Ensure your OAuth2 callback server provides clear success and error responses to indicate the authorization status.

**Note**  
If you interrupt an invocation without completing authorization, you may need to request a new URL using a new session ID ( `--session-id` parameter).

### Debugging
<a name="identity-quick-start-debugging"></a>

Should you encounter any errors or unexpected behaviors, the output of the agent is captured in Amazon CloudWatch logs. A log tailing command is provided after you run `agentcore deploy`.

## Clean up
<a name="identity-quick-start-cleanup"></a>

After you’re done, run `agentcore remove all` and then `agentcore deploy` from your project directory to tear down the deployed AgentCore Runtime resources. Then delete the Amazon Cognito user pool, detach and delete the IAM policy you created, and delete the credential provider.

## Security best practices
<a name="identity-quick-start-security"></a>

When working with identity information:

1.  **Never hardcode credentials** in your agent code

1.  **Use environment variables or Amazon SageMaker AI** for sensitive information

1.  **Apply least privilege principle** when configuring IAM permissions

1.  **Regularly rotate credentials** for external services

1.  **Audit access logs** to monitor agent activity

1.  **Implement proper error handling** for authentication failures

# Integrate with Google Drive using OAuth2
<a name="identity-getting-started-google"></a>

This getting started tutorial walks you through the essential steps to start using Amazon Bedrock AgentCore Identity for your AI agents. You’ll learn how to set up your development environment, install the necessary SDKs, create your first agent identity, and allow your agent to access external resources securely.

By the end of this tutorial, you’ll have a working agent that can retrieve access tokens from Google with AgentCore Identity OAuth2 Credential Provider, and read files from Google Drive using access tokens. For detailed information about OAuth2 flows, see [Manage credential providers with AgentCore Identity](identity-outbound-credential-provider.md).

**Topics**
+ [

## Prerequisites
](#identity-getting-started-prerequisites)
+ [

## Step 1: Set up an OAuth 2.0 Credential Provider
](#identity-getting-started-step1)
+ [

## Step 2: Import Identity and Auth modules
](#identity-getting-started-step2)
+ [

## Step 3: Obtain an OAuth 2.0 access token
](#identity-getting-started-step3)
+ [

## Step 4: Use OAuth2 Access Token to Invoke External Resource
](#identity-getting-started-step4)
+ [

## What’s Next?
](#identity-getting-started-whats-next)

## Prerequisites
<a name="identity-getting-started-prerequisites"></a>

Before you start, you need:
+ An AWS account with appropriate permissions (for example, `BedrockAgentCoreFullAccess` )
+ Python 3.10 or higher
+ The latest AWS CLI and `jq` installed
+  AWS credentials and region configured ( `aws configure` )
+ Basic understanding of Python programming

### Install the SDK
<a name="identity-getting-started-install-sdk"></a>

To get started, install the `bedrock-agentcore` package:

```
pip install bedrock-agentcore
```

### Obtain Google Client ID and Client Secret
<a name="identity-getting-started-google-credentials"></a>

To allow your agent to access Google Drive, you need to obtain a Google client ID and client secret for your agent. Go to the [Google Developer Console](https://console.developers.google.com/project) and follow these steps:

1. Create a Project in Google Developer Console

1. Enable Google Drive API

1. Configure OAuth consent screen

1. Create a new web application for the agent, for example, "My Agent 1"

1. Add the following OAuth 2.0 scope to your agent application: `https://www.googleapis.com/auth/drive.metadata.readonly` 

1. Create OAuth 2.0 Credentials for the new web application, and save the generated Google client ID and client secret

## Step 1: Set up an OAuth 2.0 Credential Provider
<a name="identity-getting-started-step1"></a>

Create a new OAuth 2.0 Credential Provider with the Google client ID and client secret obtained earlier using the following AWS CLI command:

```
OAUTH2_CREDENTIAL_PROVIDER_RESPONSE=$(aws bedrock-agentcore-control create-oauth2-credential-provider \
  --region us-east-1 \
  --name "google-provider" \
  --credential-provider-vendor "GoogleOauth2" \
  --oauth2-provider-config-input '{
      "googleOauth2ProviderConfig": {
        "clientId": "<your-google-client-id>",
        "clientSecret": "<your-google-client-secret>"
      }
    }' \
--output json)

OAUTH2_CALLBACK_URL=$(echo $OAUTH2_CREDENTIAL_PROVIDER_RESPONSE | jq -r '.callbackUrl')

echo "OAuth2 Callback URL: $OAUTH2_CALLBACK_URL"
```

**Note**  
Obtain the `callbackUrl` from the [CreateOauth2CredentialProvider](https://docs.aws.amazon.com/bedrock-agentcore-control/latest/APIReference/API_CreateOauth2CredentialProvider.html) response above and add the URI to your Google application’s redirect URI list. The callback URL should look like: https://bedrock-agentcore.us-east-1.amazonaws.com/identities/oauth2/callback/\$1\$1\$1\$1\$1\$1\$1\$1-\$1\$1\$1\$1-\$1\$1\$1\$1-\$1\$1\$1\$1-\$1\$1\$1\$1\$1\$1\$1\$1\$1\$1\$1\$1

## Step 2: Import Identity and Auth modules
<a name="identity-getting-started-step2"></a>

Add this import statement to your Python file:

```
from bedrock_agentcore.services.identity import IdentityClient
from bedrock_agentcore.identity.auth import requires_access_token, requires_api_key
```

## Step 3: Obtain an OAuth 2.0 access token
<a name="identity-getting-started-step3"></a>

Once you have the Google Credential Provider created in the previous step, add the `@requires_access_token` decorator to your agent code that requires a Google access token. Copy the authorization URL from your console output, then paste it in your browser and complete the consent flow with Google Drive.

The following code sample is intended to be integrated into your agent code to invoke an authorization workflow. This is not standalone code that can be copied and run independently.

```
import asyncio

# Injects Google Access Token
@requires_access_token(
    # Uses the same credential provider name created above
    provider_name="google-provider",
    # Requires Google OAuth2 scope to access Google Drive
    scopes=["https://www.googleapis.com/auth/drive.metadata.readonly"],
    # Sets to OAuth 2.0 Authorization Code flow
    auth_flow="USER_FEDERATION",
    # Prints authorization URL to console
    on_auth_url=lambda x: print("\nPlease copy and paste this URL in your browser:\n" + x),
    # If false, caches obtained access token
    force_authentication=False,
    # The callback URL to redirect to after the OAuth 2.0 token retrieval is complete
    callback_url='oauth2_callback_url_for_session_binding',
)
async def write_to_google_drive(*, access_token: str):
    # Prints the access token obtained from Google
    print(access_token)

asyncio.run(write_to_google_drive(access_token=""))
```

Behind the scenes, the `@requires_access_token` decorator runs through the following sequence:

![\[Flow diagram showing the sequence of API calls made by the @requires_access_token decorator\]](http://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/images/identity_access_token_flow.png)


1. The SDK makes API calls to `CreateWorkloadIdentity` , `GetWorkloadAccessToken` , and `GetResourceOauth2Token`.

1. When running the agent code locally, the SDK automatically generates an agent identity ID and a random user ID for local testing, and stores them in a local file called `.bedrock_agentcore.yaml`.

1. When running the agent code with AgentCore Runtime, the SDK does not generate an agent identity ID or random user ID. Instead, it uses the agent identity ID assigned, and the user ID or JWT token passed in by the agent caller.

1. Agent access token is an encrypted (opaque) token that contains the agent identity ID and user ID.

1. AgentCore Identity service stores the Google access token in the Token Vault under the agent identity ID and user ID. This creates a binding among the agent identity, user identity, and the Google access token.

1. The [session binding flow](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/oauth2-authorization-url-session-binding.html) must be completed before the Google access token is returned to the caller by AgentCore Identity.

## Step 4: Use OAuth2 Access Token to Invoke External Resource
<a name="identity-getting-started-step4"></a>

Once the agent obtains a Google access token with the steps above, it can use the access token to access Google Drive. Here is a full example that lists the names and IDs of the first 10 files that the user has access to.

First, install the Google client library for Python:

```
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
```

Then, copy the following code:

```
import asyncio
from bedrock_agentcore.identity.auth import requires_access_token, requires_api_key
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

SCOPES = ["https://www.googleapis.com/auth/drive.metadata.readonly"]

def main(access_token):
    """Shows basic usage of the Drive v3 API.

    Prints the names and ids of the first 10 files the user has access to.
    """
    creds = Credentials(token=access_token, scopes=SCOPES)

    try:
        service = build("drive", "v3", credentials=creds)

        # Call the Drive v3 API
        results = (
            service.files()
            .list(pageSize=10, fields="nextPageToken, files(id, name)")
            .execute()
        )
        items = results.get("files", [])

        if not items:
            print("No files found.")
            return

        print("Files:")
        for item in items:
            print(f"{item['name']} ({item['id']})")

    except HttpError as error:
        # TODO(developer) - Handle errors from drive API.
        print(f"An error occurred: {error}")

if __name__ == "__main__":
    # This annotation helps agent developer to obtain access tokens from external applications
    @requires_access_token(
        provider_name="google-provider",
        # Google OAuth2 scopes
        scopes=["https://www.googleapis.com/auth/drive.metadata.readonly"],
        # 3LO flow
        auth_flow="USER_FEDERATION",
        # prints authorization URL to console
        on_auth_url=lambda x: print("Copy and paste this authorization url to your browser", x),
        force_authentication=True,
        callback_url='oauth2_callback_url_for_session_binding',
    )
    async def read_from_google_drive(*, access_token: str):
        print(access_token)  # You can see the access_token
        # Make API calls...
        main(access_token)

    asyncio.run(read_from_google_drive(access_token=""))
```

**Note**  
For a sample local callback server implementation to handle [session binding](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/oauth2-authorization-url-session-binding.html) , refer to [https://github.com/awslabs/amazon-bedrock-agentcore-samples/blob/main/01-tutorials/03-AgentCore-identity/05-Outbound_Auth_3lo/oauth2_callback_server.py](https://github.com/awslabs/amazon-bedrock-agentcore-samples/blob/main/01-tutorials/03-AgentCore-identity/05-Outbound_Auth_3lo/oauth2_callback_server.py) 

## What’s Next?
<a name="identity-getting-started-whats-next"></a>

The example in this section focuses on practical implementation patterns that you can adapt for your specific use cases. You can embed the code as part of an agent, or a Model Context Protocol (MCP) tool. If you want to host your Agent code or MCP Tool with AgentCore Runtime, follow [Host agent or tools with Amazon Bedrock AgentCore Runtime](agents-tools-runtime.md) to copy the code above to AgentCore Runtime.

# Using the AgentCore Identity console
<a name="identity-how-to"></a>

The AgentCore Identity console provides a centralized interface for managing your agent authentication configurations. You can use the console to set up outbound identity providers for external service access, configure inbound identity settings for agent authentication, and manage API keys for services that require key-based authentication. This section contains step-by-step procedures for all console-based AgentCore Identity tasks.

**Topics**
+ [

# Configure an OAuth client
](identity-oauth-client.md)
+ [

# Configure an API key
](identity-api-key.md)

# Configure an OAuth client
<a name="identity-oauth-client"></a>

An OAuth client enables your agent to securely access external services on behalf of users without requiring them to share their credentials directly. For example, your agent can access a user’s Google Drive files or Microsoft calendar events through OAuth authentication.

**Topics**
+ [

# Add OAuth client using included provider
](identity-add-oauth-client-included.md)
+ [

# Add OAuth client using custom provider
](identity-add-oauth-client-custom.md)
+ [

# Update OAuth client
](identity-update-oauth-client.md)
+ [

# Delete OAuth client
](identity-delete-oauth-client.md)

# Add OAuth client using included provider
<a name="identity-add-oauth-client-included"></a>

Built-in providers offer streamlined setup for popular services including Google, GitHub, Slack, and Salesforce. These providers have pre-configured authorization server endpoints and provider-specific parameters to reduce development effort.

 **To add an OAuth client using an included provider** 

1. Open the [AgentCore Identity](https://console.aws.amazon.com/bedrock-agentcore/identity) console.

1. In the **Outbound Auth** section, choose **Add OAuth client / API key** , and then select **Add OAuth client**.

1. For **Name** , you can either use the auto-generated name or enter your own descriptive name to help you identify this OAuth client in your account. Use alphanumeric characters, hyphens, and underscores only, with a maximum length of 50 characters.

1. For **Provider** , choose **Included provider**.

1. Choose your identity provider from the available options (Google, GitHub, Microsoft, Salesforce, or Slack).

1. In the **Provider configurations** section, enter your client credentials:

   1. For **Client ID** , enter the unique identifier you received when registering your application with the identity provider.

   1. For **Client secret** , enter the confidential key associated with your client ID. AgentCore Identity securely stores this value for authentication.

1. Choose **Add OAuth Client**.

After creating the OAuth client, AgentCore Identity provides an ARN that you can reference in your agent code to request authentication tokens without embedding sensitive credentials in your application. You can find this ARN in the properties page of the OAuth client (Choose the client name in the **Outbound Auth** section).

# Add OAuth client using custom provider
<a name="identity-add-oauth-client-custom"></a>

Custom providers enable you to connect to any OAuth2-compatible resource server beyond the built-in provider options. You can configure custom providers by having the system retrieve configuration details automatically, or by providing the server information manually.

 **To add an OAuth client using a custom provider** 

1. Open the [AgentCore Identity](https://console.aws.amazon.com/bedrock-agentcore/identity) console.

1. In the **Outbound Auth** section, choose **Add OAuth client / API key** , and then select **Add OAuth client**.

1. For **Name** , you can either use the auto-generated name or enter your own descriptive name to help you identify this OAuth client in your account. Use alphanumeric characters, hyphens, and underscores only, with a maximum length of 50 characters.

1. For **Provider** , choose **Custom provider**.

1. In the **Provider configurations** section, depending on your provider requirements, choose one of the following options:

   1.  **Discovery URL** (recommended) – Choose this option to have AgentCore Identity automatically retrieve configuration details from your provider. You provide the discovery URL where your provider publishes its OpenID Connect configuration, and AgentCore Identity handles the endpoint discovery process. This is the recommended approach when available as it reduces manual configuration.

      1. For **Client ID** , enter the unique identifier you received when registering your application with the identity provider.

      1. For **Client secret** , enter the confidential key associated with your client ID that AgentCore Identity securely stores for authentication.

      1. For **Discovery URL** , enter the URL where your provider publishes its OpenID Connect configuration. Discovery URLs must end with `.well-known/openid-configuration` . For example, https:// *example.com* /.well-known/openid-configuration.

   1.  **Manual config** – Choose this option to specify server information directly when your provider doesn’t support automatic discovery. You’ll define each endpoint URL individually, giving you complete control over the configuration details.

      1. For **Client ID** , enter the unique identifier you received when registering your application with the identity provider.

      1. For **Client secret** , enter the confidential key associated with your client ID that AgentCore Identity securely stores for authentication.

      1. For **Issuer** , enter the base URL that identifies your authorization server. This value appears in the `iss` claim of issued tokens and helps verify token authenticity.

      1. For **Authorization endpoint** , enter the URL where users will be directed to grant permission to your application. This is the entry point for the OAuth authorization flow.

      1. For **Token endpoint** , enter the URL where your agent exchanges authorization codes for access tokens. This endpoint handles the credential exchange process.

      1. (Optional) In the **Response types** section, configure how your OAuth client receives authentication responses by choosing **Add response type** and selecting the token formats your provider should return. Common types include `code` for authorization code flow or `token` for implicit flow.

1. Choose **Add OAuth Client**.

After completing either configuration, AgentCore Identity securely stores your OAuth settings and provides an ARN you can reference in your agent code, enabling token requests without embedding sensitive credentials in your application. You can find this ARN in the properties page of the OAuth client (Choose the client name in the **Outbound Auth** section).

# Update OAuth client
<a name="identity-update-oauth-client"></a>

You can modify the configuration settings for your existing OAuth client. For example, you can update your client credentials (Client ID and Client secret) when they’ve been rotated or changed by your identity provider.

 **To update an OAuth client** 

1. Open the [AgentCore Identity](https://console.aws.amazon.com/bedrock-agentcore/identity) console.

1. In the **Outbound Auth** section, select the OAuth client you want to update.

1. Choose **Edit**.

1. On the **Update OAuth Client** page, update the information as needed.

1. Choose **Update OAuth Client** to save your configuration settings.

The updated OAuth client configuration takes effect immediately and will be used for all subsequent authentication requests made by your agents.

# Delete OAuth client
<a name="identity-delete-oauth-client"></a>

When you no longer need an OAuth client, you can delete it from your account. Deleting an OAuth client removes the stored configuration and credentials, making them unavailable to your agents. Any invocations that reference the deleted OAuth client will fail once it’s removed, and this outbound authentication might be used across multiple runtimes and gateways.

 **To delete an OAuth client** 

1. Open the [AgentCore Identity](https://console.aws.amazon.com/bedrock-agentcore/identity) console.

1. In the **Outbound Auth** section, select the OAuth client you want to delete.

1. Choose **Delete**.

1. In the confirmation dialog, type `Delete` to confirm the deletion.

1. Choose **Delete**.

The OAuth client is permanently removed from your account. Any agents or applications that reference this OAuth client’s ARN will no longer be able to access the stored credentials.

# Configure an API key
<a name="identity-api-key"></a>

API keys provide key-based authentication for services that require direct key access with secure storage capabilities. An API key is a unique identifier used to authenticate and authorize access to a resource, enabling your agent to access external services without embedding sensitive credentials directly in your application code.

**Topics**
+ [

# Add API key
](identity-add-api-key.md)
+ [

# Update API key
](identity-update-api-key.md)
+ [

# Delete API key
](identity-delete-api-key.md)

# Add API key
<a name="identity-add-api-key"></a>

API keys provide key-based authentication for services that require direct key access with secure storage capabilities. An API key is a unique identifier used to authenticate and authorize access to a resource, enabling your agent to access external services without embedding sensitive credentials directly in your application code.

 **To add an API key** 

1. Open the [AgentCore Identity](https://console.aws.amazon.com/bedrock-agentcore/identity) console.

1. In the **Outbound Auth** section, choose **Add OAuth client / API key** , then choose **Add API key**.

1. For **Name** , you can either use the auto-generated name or enter your own descriptive name to help you identify this API key in your account. Use alphanumeric characters, hyphens, and underscores only, with a maximum length of 50 characters.

1. For **API key** , enter the key value provided by your external service. AgentCore Identity securely stores this value and makes it available to your agent at runtime.

1. Choose **Add**.

After creating the API key, AgentCore Identity provides an ARN that you can reference in your agent code to access the stored key without exposing sensitive information in your application. You can find this ARN in the properties page of the API key (Choose the API key name in the **Outbound Auth** section).

# Update API key
<a name="identity-update-api-key"></a>

You can update an existing API key to replace the key value when your external service provider rotates credentials. Updating the API key ensures your agents continue to have access to the external service with the current authentication information.

 **To update an API key** 

1. Open the [AgentCore Identity](https://console.aws.amazon.com/bedrock-agentcore/identity) console.

1. In the **Outbound Auth** section, select the API key you want to update.

1. Choose **Edit**.

1. In the **Update API key** dialog, in **API key** , enter the updated key value provided by your external service. AgentCore Identity securely stores this new value and makes it available to your agent at runtime.

1. Choose **Update**.

The updated API key configuration takes effect immediately. Your agents will use the new API key for all subsequent requests to the external service.

# Delete API key
<a name="identity-delete-api-key"></a>

When you no longer need an API key, you can delete it from your account. Deleting an API key removes the stored credentials and makes them unavailable to your agents. Any invocations that reference the deleted API key will fail once it’s removed.

 **To delete an API key** 

1. Open the [AgentCore Identity](https://console.aws.amazon.com/bedrock-agentcore/identity) console.

1. In the **Outbound Auth** section, select the API key you want to delete.

1. Choose **Delete**.

1. In the confirmation dialog, type `Delete` to confirm the deletion.

1. Choose **Delete**.

The API key is permanently removed from your account. Any agents or applications that reference this API key’s ARN will no longer be able to access the stored credentials.

# Manage workload identities with AgentCore Identity
<a name="identity-manage-agent-ids"></a>

Agent identities in AgentCore Identity are implemented as workload identities with specialized attributes that enable agent-specific capabilities. This approach follows established industry patterns where workloads have granular properties that indicate their specific type and purpose. Unlike traditional service accounts that are tied to specific infrastructure, agent identities are designed to be environment-agnostic and can support multiple authentication credentials simultaneously. The AgentCore Identity directory acts as a centralized registry and management system for all agent identities. For information about workload identity limits, see [AgentCore Identity Service Quotas](bedrock-agentcore-limits.md#identity-service-limits).

**Topics**
+ [

# Understanding workload identities
](understanding-agent-identities.md)
+ [

# Understanding the agent identity directory
](agent-identity-directory.md)
+ [

# Create and manage workload identities
](creating-agent-identities.md)

# Understanding workload identities
<a name="understanding-agent-identities"></a>

Workload identities represent the digital identity of your agents within the AWS environment. They serve as a stable anchor point that persists across different deployment environments and authentication schemes, allowing agents to maintain consistent identity whether they’re using IAM roles for AWS resource access, OAuth2 tokens for external service integration, or API keys for third-party tool access. The identity system abstracts the complexity of managing multiple credential types while providing a unified interface for authentication and authorization operations.

Workload identities integrate seamlessly with the broader AgentCore Identity framework, including the token vault for secure credential storage (see [Secure credential storage](key-features-and-benefits.md#secure-credential-storage) ), Resource credential providers for external service access (see [Configure credential provider](resource-providers.md) ), and the AgentCore Identity directory for centralized management. For more information about the directory, see [Understanding the agent identity directory](agent-identity-directory.md).

**Topics**
+ [

## How workload identities are created
](#workload-identity-creation)

## How workload identities are created
<a name="workload-identity-creation"></a>

Workload identities are created automatically in several scenarios and can also be created manually when needed. These identities are used to obtain workload access tokens that authorize agent access to credentials. For details about how workload identities are used in the authentication flow, see [Get workload access token](get-workload-access-token.md).

 **Automatic creation by Runtime and Gateway** 
+ When you deploy an agent using AgentCore Runtime, a workload identity is automatically created and associated with your agent
+ AgentCore Gateway also creates workload identities automatically for agents deployed through the gateway service
+ These automatically created identities are managed by the service and include the necessary settings for your deployment environment
+ The workload identity ARN is returned in the deployment response and can be used for IAM policies and access control

 **Manual creation for custom deployments** 
+ For agents not hosted by Runtime or Gateway (such as self-hosted or hybrid deployments), you can manually create workload identities
+ Use the [CreateWorkloadIdentity API](https://docs.aws.amazon.com/bedrock-agentcore-control/latest/APIReference/API_CreateWorkloadIdentity.html) or AWS CLI to create identities for custom agent deployments
+ Manual creation gives you control over the identity name and metadata
+ This approach is ideal when you need specific identity names or are integrating with existing identity management systems

 **When to use each approach** 
+ Use automatic creation when deploying through AgentCore Runtime or Gateway for simplified setup
+ Use manual creation when you need specific identity names or are deploying agents in non-standard environments
+ Manual creation is also useful for testing scenarios or when you need multiple identities for the same agent in different environments

Workload identities are used to obtain workload access tokens that authorize agent access to credentials. For details about how workload identities are used in the authentication flow, see [Get workload access token](get-workload-access-token.md).

Once you have created workload identities, you can use them to control access to credential providers. For information about implementing fine-grained access control, see [Scope down access to credential providers by workload identity](scope-credential-provider-access.md).

# Understanding the agent identity directory
<a name="agent-identity-directory"></a>

The agent identity directory is a centralized collection of all workload identities within your AWS account. It serves as the authoritative registry for managing and organizing agent identities, providing a unified view of all identities whether they were created automatically by AgentCore Runtime and Gateway or manually through the AWS CLI and SDK. For information about creating workload identities, see [Create and manage workload identities](creating-agent-identities.md).

**Topics**
+ [

## Directory concepts and structure
](#directory-concepts)
+ [

## Directory management best practices
](#directory-management-best-practices)
+ [

## Listing and viewing directory contents
](#listing-directory-contents)
+ [

## Directory access control and permissions
](#directory-access-control)

## Directory concepts and structure
<a name="directory-concepts"></a>

Understanding the fundamental concepts and organizational structure of the agent identity directory helps you effectively manage workload identities at scale.

 **Key characteristics** 
+  **Single directory per account** – Each AWS account has exactly one agent identity directory
+  **Automatic creation** – The directory is automatically created when the first workload identity is created in your account
+  **Centralized management** – All workload identities, regardless of how they were created, are stored in this directory
+  **Cross-service visibility** – The directory provides visibility into identities created by Runtime, Gateway, and manual processes

 **Directory structure** 

```
arn:aws:bedrock-agentcore:region:account-id:workload-identity-directory/default
├── workload-identity/runtime-created-agent-1
├── workload-identity/runtime-created-agent-2
├── workload-identity/gateway-created-agent-1
├── workload-identity/manually-created-agent-1
└── workload-identity/manually-created-agent-2
```

## Directory management best practices
<a name="directory-management-best-practices"></a>

Following established best practices for directory management helps maintain organization, security, and operational efficiency as your workload identity usage grows.

 **Naming conventions** 
+ Use descriptive names that indicate the agent’s purpose (such as "customer-support-agent", "data-analysis-agent")
+ Include environment indicators for multi-environment deployments (such as "prod-chatbot", "dev-chatbot")
+ Consider team or project prefixes for large organizations (such as "marketing-content-agent")

 **Organization strategies** 
+ Regularly audit your directory to identify unused or obsolete workload identities
+ Document the purpose and ownership of each workload identity
+ Implement consistent tagging strategies for workload identities when available. For more information, see [Tagging AgentCore Identity resources](identity-tagging.md).
+ Monitor directory growth and establish governance processes for identity creation

 **Security considerations** 
+ Regularly review IAM policies that grant access to the directory
+ Use least-privilege principles when granting directory access
+ Monitor directory access through AWS CloudTrail logs
+ Implement automated alerts for unauthorized directory modifications

## Listing and viewing directory contents
<a name="listing-directory-contents"></a>

You can view all workload identities in your directory using the AWS CLI:

 **List all workload identities** 

```
aws bedrock-agentcore-control list-workload-identities
```

This command returns information about all workload identities in your account, including:
+ Workload identity names and ARNs
+ Creation timestamps
+ Associated metadata
+ Creation source (Runtime, Gateway, or manual)

 **Example output** 

```
{
  "workloadIdentities": [
    {
      "workloadIdentityArn": "arn:aws:bedrock-agentcore:us-east-1:123456789012:workload-identity-directory/default/workload-identity/my-runtime-agent",
      "workloadIdentityName": "my-runtime-agent",
      "createdAt": "2024-01-15T10:30:00Z",
      "createdBy": "AgentCore Runtime"
    },
    {
      "workloadIdentityArn": "arn:aws:bedrock-agentcore:us-east-1:123456789012:workload-identity-directory/default/workload-identity/my-custom-agent",
      "workloadIdentityName": "my-custom-agent",
      "createdAt": "2024-01-16T14:20:00Z",
      "createdBy": "Manual"
    }
  ]
}
```

 **Get details about a specific workload identity** 

```
aws bedrock-agentcore-control get-workload-identity \
    --workload-identity-name my-agent-name
```

## Directory access control and permissions
<a name="directory-access-control"></a>

The agent identity directory integrates with IAM to provide fine-grained access control over workload identities and their associated resources. For information about using workload identities to control access to credential providers, see [Scope down access to credential providers by workload identity](scope-credential-provider-access.md).

 **Directory-level permissions** 
+  **List permissions** – Control who can view the directory contents
+  **Create permissions** – Control who can create new workload identities
+  **Read permissions** – Control who can view specific workload identity details
+  **Delete permissions** – Control who can remove workload identities

 **Example IAM policy for directory access** 

```
{
"Version": "2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "ListWorkloadIdentities",
      "Effect": "Allow",
      "Action": [
        "bedrock-agentcore:ListWorkloadIdentities"
      ],
      "Resource": [
        "arn:aws:bedrock-agentcore:*:*:workload-identity-directory/default"
      ]
    },
    {
      "Sid": "ManageSpecificWorkloadIdentity",
      "Effect": "Allow",
      "Action": [
        "bedrock-agentcore:GetWorkloadIdentity",
        "bedrock-agentcore:CreateWorkloadIdentity",
        "bedrock-agentcore:DeleteWorkloadIdentity"
      ],
      "Resource": [
        "arn:aws:bedrock-agentcore:*:*:workload-identity-directory/default/workload-identity/my-agent-*"
      ]
    }
  ]
}
```

# Create and manage workload identities
<a name="creating-agent-identities"></a>

You can create agent identities using several methods, including the AWS CLI and the AgentCore SDK, depending on your workflow and integration requirements. AgentCore Identity provides multiple interfaces for identity creation including command-line tools for automation and scripting and programmatic APIs for integration with existing systems. Each creation method supports the full range of identity properties while providing appropriate interfaces for different use cases and user preferences.

**Topics**
+ [

## Manage identities with AWS CLI
](#cli-creation)
+ [

## Create identities with the AgentCore SDK
](#sdk-creation)

## Manage identities with AWS CLI
<a name="cli-creation"></a>

The AWS CLI provides a straightforward way to create and delete agent identities.

 **Create an identity** 

The following command creates a workload identity named *my-agent*.

```
aws bedrock-agentcore-control create-workload-identity \
    --name "my-agent"
```

 **List all identities** 

The following command lists all workload identities in your account.

```
aws bedrock-agentcore-control list-workload-identities
```

 **Delete an identity** 

The following command deletes the workload identity named *my-agent*.

```
aws bedrock-agentcore-control delete-workload-identity \
    --name "my-agent"
```

## Create identities with the AgentCore SDK
<a name="sdk-creation"></a>

The AgentCore SDK provides support for creating workload identities in Python.

 **Python example** 

The following Python code creates a workload identity using the AgentCore SDK.

```
from bedrock_agentcore.services.identity import IdentityClient

# Initialize the client
identity_client = IdentityClient("us-east-1")

# Create a new workload identity for agent
response = identity_client.create_workload_identity(name='my-python-agent')
agentArn = response['workloadIdentityArn']

print(f"Created agent identity with ARN: {agentArn}")
```

# Configure inbound JWT authorizer
<a name="inbound-jwt-authorizer"></a>

The inbound authorizer authenticates and authorizes incoming OAuth 2.0 API requests to AgentCore Runtime and AgentCore Gateway. It validates JSON Web Tokens (JWTs) before allowing access to agents or gateways. The authorizer is Identity Provider (IdP) agnostic and works with any OAuth 2.0 compatible identity provider. When AgentCore Runtime or AgentCore Gateway receives an inbound request, the authorizer will use the configured discovery URL to fetch the public keys and authorization server endpoint to perform the JWT validation. You can configure the authorizer based on your IdP and allowed authorization scopes or claims.

## Configure an Inbound Authorizer
<a name="configure-inbound-authorizer"></a>

You can configure your agent runtime (see [CreateAgentRuntime](https://docs.aws.amazon.com/bedrock-agentcore-control/latest/APIReference/API_CreateAgentRuntime.html) ) or gateway (see [CreateGateway](https://docs.aws.amazon.com/bedrock-agentcore-control/latest/APIReference/API_CreateGateway.html) ) to accept JWT bearer tokens by providing an authorizer configuration during agent or gateway creation. The authorization configuration (see [CustomJWTAuthorizerConfiguration](https://docs.aws.amazon.com/bedrock-agentcore-control/latest/APIReference/API_CustomJWTAuthorizerConfiguration.html) ) is the same for either AgentCore Runtime or AgentCore Gateway.
+  **Discovery URL** : A string that must match the pattern `^.+/\.well-known/openid-configuration$` for OpenID Connect (OIDC) discovery URLs. You can find your discovery URL from your identity provider. A discovery URL is a specific web address that AgentCore Identity can use to find information about the authentication endpoint details. It allows AgentCore Identity to dynamically accept tokens issued by your OIDC identity provider without explicit onboarding.
+  **Allowed audiences** : A list of permitted audiences that AgentCore Identity will validate against the `aud` claim in the JWT token. An audience claim ( `aud` ) in OAuth 2.0 specifies which resource server (API) the token is intended for. The resource server validates the `aud` claim to ensure it is the correct recipient before processing the request, preventing a token from being reused at a different API it was not issued for.
+  **Allowed clients** : A list of permitted client identifiers that AgentCore Identity will validate against the `client_id` claim in the JWT token. A `client_id` in OAuth 2.0 is a public, unique identifier for an application that is requesting access tokens to access AgentCore Runtime or AgentCore Gateway. It acts like a username for the application, distinguishing it from other clients (applications) registered with the authorizer.
+  **Allowed scopes** : A list of permitted permissions, defined as scopes, allowed to invoke the runtime or gateway. If configured, at least one scope value in the incoming token must match one of the configured values. An OAuth 2.0 scope is a string that defines a specific level of access that is defined in the JWT. Scopes act as permissions to limit what an application can do.
+  **Required custom claims (see CustomClaimValidationType)** : A set of rules to match specific claims in the incoming token against predefined values for validating JWT tokens. You can create a rule by specifying the following:
  +  **InboundTokenClaimName** : Name of the custom claim.
  +  **InboundTokenClaimValueType** : Either `STRING` or `STRING_ARRAY`.
  +  **AuthorizingClaimMatchValue** : Required value and comparison operator of the custom claim.
    +  **ClaimMatchValue** : Required value of the custom claim.
    +  **ClaimMatchOperator** : If `InboundTokenClaimValueType` equals `STRING` , this must be `EQUALS` . If `InboundTokenClaimValueType` equals `STRING_ARRAY` , this can be `CONTAINS` or `CONTAINS_ANY`.
    +  **Example** : You can define a rule that enforces: `Group must equal Developer`.
+  **Note** : At least one of the fields is required for the configuration: allowed audiences, allowed clients, allowed scopes, or required custom claims. If more than one is used, the authorizer will verify them all.

# Manage credential providers with AgentCore Identity
<a name="identity-outbound-credential-provider"></a>

Credential management is a core feature of Amazon Bedrock AgentCore Identity that addresses the complex challenge of securely storing, retrieving, and managing credentials across multiple trust domains and authentication systems. The service implements defense-in-depth security measures to protect sensitive authentication tokens, API keys, and certificates while providing agents with efficient access to the credentials they need for authorized operations. AgentCore Identity’s credential management architecture separates credential storage from credential access, helping to ensure that agents never have direct access to long-term secrets or refresh tokens.

The credential management system supports multiple credential types including OAuth2 access tokens, API keys, client certificates, SAML assertions, and custom authentication tokens. Each credential type has specific handling requirements for storage encryption and access patterns. All credential operations are logged and audited to provide complete visibility into credential usage and access patterns.

Integration with the Resource Credential Provider enables AgentCore Identity to support cross-capability credential vending, where agents can access resources across different cloud providers, SaaS applications, and enterprise systems using a unified credential management interface. The system maintains proper security boundaries while enabling necessary functionality, with comprehensive monitoring and alerting capabilities that detect unusual credential usage patterns or potential security threats.

**Topics**
+ [

# Supported authentication patterns
](common-use-cases.md)
+ [

# Configure credential provider
](resource-providers.md)
+ [

# Obtain credentials
](obtain-credentials.md)

# Supported authentication patterns
<a name="common-use-cases"></a>

AgentCore Identity supports two primary authentication patterns that address different agent use cases. Understanding these patterns will help you choose the right approach for your specific agent implementation.

For detailed examples of how these patterns apply to specific industries and agent types, see [Example use cases](identity-use-cases.md).

**Topics**
+ [

## User-delegated access (OAuth 2.0 authorization code grant)
](#user-delegated-access)
+ [

## Machine-to-machine authentication (OAuth 2.0 client credentials grant)
](#machine-to-machine-auth)
+ [

## Choosing the right authentication pattern
](#choosing-auth-pattern)

## User-delegated access (OAuth 2.0 authorization code grant)
<a name="user-delegated-access"></a>

The OAuth 2.0 authorization code grant flow enables agents to access user-specific data with explicit user consent. This pattern is essential when agents need to access personal data or perform actions on behalf of specific users. The flow includes a user consent step where the resource owner (user) explicitly authorizes the agent to access their data within specific scopes.

 **Key characteristics** 
+ Requires explicit user consent through an authorization prompt
+ Provides access to user-specific data and resources
+ Maintains clear separation between agent identity and user authorization
+ Supports fine-grained scopes that limit what data the agent can access

 **Example scenario** – A productivity agent needs to access a user’s Google Calendar to schedule meetings, their Gmail to send emails, and their Google Drive to store documents. The agent uses the OAuth 2.0 authorization code grant to obtain user consent for each service, with specific scopes that limit access to only the necessary data. The user explicitly authorizes the agent through Google’s consent screen, and AgentCore Identity securely stores the resulting credentials for future use.

This pattern is ideal for personal assistant agents, customer service agents, and any scenario where agents need access to user-specific data across multiple services. For detailed industry-specific examples, see [Personal assistant agents](identity-use-cases.md#personal-assistant-agents) and [Customer service agents](identity-use-cases.md#customer-service-agents).

## Machine-to-machine authentication (OAuth 2.0 client credentials grant)
<a name="machine-to-machine-auth"></a>

The OAuth 2.0 client credentials grant flow enables direct authentication between systems without user interaction. This pattern is appropriate when agents need to access resources that aren’t user-specific or when agents act themselves with pre-authorized user consent.

 **Key characteristics** 
+ No user interaction or consent required
+ Agent authenticates directly with resource servers using its own credentials
+ Suitable for background processes, scheduled tasks, and system-level operations
+ Permissions are defined at the agent level rather than per-user

 **Example scenario** – An enterprise data processing agent needs to collect data from multiple internal systems, process it, and store the results in a data warehouse. The agent uses the OAuth 2.0 client credentials grant to authenticate directly with each system using its own identity and pre-configured permissions. No user interaction is required, and the agent can operate when agents act themselves with pre-authorized user consent on scheduled intervals.

This pattern is ideal for enterprise automation agents, data processing workflows, and DevOps automation. For detailed industry-specific examples, see [Enterprise automation agents](identity-use-cases.md#enterprise-automation-agents) , [Data processing and analytics agents](identity-use-cases.md#data-processing-and-analytics-agents) , and [Development and DevOps agents](identity-use-cases.md#development-and-devops-agents).

## Choosing the right authentication pattern
<a name="choosing-auth-pattern"></a>

When designing your agent authentication strategy, consider these factors to determine which pattern is most appropriate:


| Factor | User-delegated access (OAuth 2.0 authorization code grant) | Machine-to-machine authentication (OAuth 2.0 client credentials grant) | 
| --- | --- | --- | 
|  Data ownership  |  User-specific data (emails, documents, personal calendars)  |  System or organization-owned data (analytics, logs, shared resources)  | 
|  User interaction  |  User is present and can provide consent  |  No user interaction required or available  | 
|  Operation timing  |  Interactive, real-time operations  |  Background, scheduled, or batch operations  | 
|  Permission scope  |  Permissions vary by user and their consent choices  |  Consistent permissions defined at the agent level  | 

Many agent implementations will require both patterns for different aspects of their functionality. For example, a customer service agent might use user-delegated access to retrieve a specific customer’s data while using machine-to-machine authentication to access company knowledge bases and internal systems. AgentCore Identity supports both patterns simultaneously, allowing agents to use the most appropriate authentication mechanism for each resource they need to access.

Both authentication patterns benefit from AgentCore Identity’s core capabilities:
+ Secure credential storage without exposing secrets to agent code
+ Consistent authentication interfaces across multiple resource types
+ Comprehensive audit logging for security and compliance
+ Fine-grained access controls based on identity and context
+ Simplified integration through the AgentCore SDK

# Configure credential provider
<a name="resource-providers"></a>

Resource credential providers in AgentCore Identity act as intelligent intermediaries that manage the complex relationships between agents, identity providers, and resource servers. Each provider encapsulates the specific endpoint configuration required for a particular service or identity system. The service provides built-in providers for popular services including Google, GitHub, Slack, and Salesforce, with authorization server endpoints and provider-specific parameters pre-configured to reduce development effort. AgentCore Identity supports custom configurations through configurable OAuth2 credential providers that can be tailored to work with any OAuth2-compatible resource server. For information about OAuth2 credential provider limits, see [AgentCore Identity Service Quotas](bedrock-agentcore-limits.md#identity-service-limits).

Resource credential providers integrate deeply with the token vault to provide seamless credential lifecycle management. When an agent requests access to a resource, the provider handles the authentication flow, stores the resulting credentials in the token vault, and provides the agent with the necessary access tokens.

## Creating an OAuth 2.0 credential provider
<a name="provider-configuration"></a>

Provider configurations in AgentCore Identity define the basic parameters needed for credential management with different resources and authentication systems.

If you are using the AgentCore CLI, you can create an OAuth 2.0 credential provider with the `agentcore add credential` command:

```
agentcore add credential --type oauth \
  --name github-provider \
  --discovery-url https://your-idp/.well-known/openid-configuration \
  --client-id your-github-client-id \
  --client-secret your-github-client-secret \
  --scopes repo,user
```

The CLI stores the credential configuration in `agentcore/agentcore.json` and saves sensitive values (client ID and client secret) to `agentcore/.env.local`.

Alternatively, you can use the AgentCore SDK to configure an OAuth 2.0 credential provider programmatically. The following example configures a provider for GitHub.

```
from bedrock_agentcore.services.identity import IdentityClient
identity_client = IdentityClient("us-east-1")
github_provider = identity_client.create_oauth2_credential_provider({
        "name": "github-provider",
        "credentialProviderVendor": "GithubOauth2",
        "oauth2ProviderConfigInput": {
            "githubOauth2ProviderConfig": {
                "clientId": "your-github-client-id",
                "clientSecret": "your-github-client-secret"
            }
        }
    })
```

## Creating an API key credential provider
<a name="api-key-management"></a>

For services that use API keys for authentication rather than OAuth, AgentCore Identity will securely store and retrieve keys for your agents. For information about API key credential provider limits, see [AgentCore Identity Service Quotas](bedrock-agentcore-limits.md#identity-service-limits).

If you are using the AgentCore CLI, you can store an API key with a single command:

```
agentcore add credential --name your-service-name --api-key your-api-key
```

Alternatively, you can use the AgentCore SDK to store an API key programmatically:

```
from bedrock_agentcore.services.identity import IdentityClient
identity_client= IdentityClient("us-east-1")
apikey_provider= identity_client.create_api_key_credential_provider({
        "name": "your-service-name",
        "apiKey": "your-api-key"
    })
```

# Obtain credentials
<a name="obtain-credentials"></a>

AgentCore Identity uses a workload access token to authorize agent access to credentials stored in the vault, and this token contains both the identity of the agent and the identity of the end user on whose behalf the agent is working. AgentCore Runtime will automatically provide a token when invoking an agent that it is hosting. Agents hosted on other systems can retrieve their agent token using the AgentCore SDK.

**Topics**
+ [

# Get workload access token
](get-workload-access-token.md)
+ [

# Obtain OAuth 2.0 access token
](identity-authentication.md)
+ [

# OAuth 2.0 authorization URL session binding
](oauth2-authorization-url-session-binding.md)
+ [

# Scope down access to credential providers by workload identity
](scope-credential-provider-access.md)
+ [

# Obtain API key
](obtain-api-key.md)

# Get workload access token
<a name="get-workload-access-token"></a>

Understanding what workload access tokens are, how to obtain them, and the security aspects of working with them is essential for building secure agent applications. This section covers the key concepts and implementation patterns you need to know.

**Topics**
+ [

## What is a workload access token?
](#workload-access-token-overview)
+ [

## How Runtime and Gateway automatically obtain tokens
](#how-runtime-gateway-obtain-tokens)
+ [

## How to manually retrieve workload access tokens
](#manual-token-retrieval-patterns)
+ [

## Security controls for `GetWorkloadAccessTokenForUserId` API
](#security-controls-getuserid-api)

## What is a workload access token?
<a name="workload-access-token-overview"></a>

A workload access token is an AWS-signed opaque access token that enables agents to access first-party AgentCore services, such as outbound credential providers. Runtime automatically delivers workload access tokens to agent execution instances as payload headers, eliminating the need for manual token management in most scenarios.

 **Key characteristics** 
+  **First-party services only** – Workload access tokens are exclusively for accessing AWS first-party AgentCore services and cannot be used for external services
+  **Automatic delivery** – Runtime and Gateway automatically provide these tokens to agents during execution
+  **Security by design** – Runtime-managed agent identities cannot retrieve workload access tokens directly, preventing token extraction and misuse
+  **User and agent identity binding** – Tokens contain both user identity and agent identity information for secure credential access

## How Runtime and Gateway automatically obtain tokens
<a name="how-runtime-gateway-obtain-tokens"></a>

When an agent is invoked through AgentCore Runtime or Gateway with inbound authentication, the service automatically handles workload access token generation:

1. Runtime validates the inbound identity provider OAuth token (issuer, signature)

1. Runtime extracts issuer and sub claims from the OAuth token representing user identity

1. Runtime fetches the associated workload identity of the agent

1. Runtime invokes `GetWorkloadAccessTokenForJWT` with both user identity and agent workload identity

1. Runtime passes the workload access token to agent code as part of the invocation payload header

This automatic process ensures agents receive properly scoped tokens without manual intervention.

## How to manually retrieve workload access tokens
<a name="manual-token-retrieval-patterns"></a>

There are two patterns to use to retrieve the workload access token depending on how you are able to identify the end user of the agent:
+ If the agent’s caller has a JWT identifying the end user, request a workload access token based on the agent’s identity and the end-user JWT. When you provide a JWT, AgentCore Identity will validate the JWT to ensure it is correctly signed and unexpired, and it will use its “iss” and “sub” claims to uniquely identify the user. Credentials stored by the agent on behalf of the user will be associated with this information, and future retrievals by the agent will require a valid workload access token containing the same information.
+ If the agent’s caller does not have a JWT identifying the end user, request a workload access token based on the agent’s identity and a unique string identifying the user.

The examples below illustrate using the AgentCore SDK to retrieve a workload access token using these two methods:

```
from bedrock_agentcore.services.identity import IdentityClient

identity_client= IdentityClient("us-east-1")# Obtain a token using the IAM identity of the caller to authenticate the agent and providing a JWT containing the identity of the end user.
# This is the recommended pattern whenever a JWT is available for the user.
workload_access_token= identity_client.get_workload_access_token(workload_name= "my-demo-agent", user_token= "insert-jwt-here")# Obtain a token using the IAM identity of the caller to authenticate the agent and providing a string representing the identity of the end user.
# Use this pattern when a JWT is not available for the user.
workload_access_token= identity_client.get_workload_access_token(workload_name= "my-demo-agent", user_id= "insert-user-name-or-identifier")
```

## Security controls for `GetWorkloadAccessTokenForUserId` API
<a name="security-controls-getuserid-api"></a>

The `GetWorkloadAccessTokenForUserId` API implements several security controls to prevent unauthorized access:
+  **Workload identity validation** – The API verifies that the requesting identity has permission to act on behalf of the specified workload identity
+  **Service-managed identity restriction** – Runtime-managed and Gateway-managed workload identities cannot retrieve tokens directly. This prevents agents from extracting tokens for misuse
+  **IAM permission requirements** – Callers must have appropriate IAM permissions including `GetWorkloadAccessToken` , `GetWorkloadAccessTokenForUserId` , and `GetWorkloadAccessTokenForJWT` 
+  **Token scoping** – Tokens are scoped to the specific user-agent pair, ensuring credentials stored under one user cannot be accessed by another
+  **User ID partitioning for multiple identity providers** – When using multiple identity providers, partition your user IDs using the pattern `provider_id+user_id` to prevent user collisions between different providers. For example, use `cognito+user123` and `auth0+user123` to distinguish users with the same identifier across different identity providers

If you encounter the error "WorkloadIdentity is linked to a service and cannot retrieve an access token by the caller," this indicates the workload identity is managed by Runtime or Gateway and cannot retrieve tokens directly. This restriction helps maintain security boundaries and prevents unauthorized token access.

For additional security controls, you can implement fine-grained access policies to restrict which workload identities can access specific credential providers. For more information, see [Scope down access to credential providers by workload identity](scope-credential-provider-access.md).

# Obtain OAuth 2.0 access token
<a name="identity-authentication"></a>

AgentCore Identity enables developers to obtain OAuth tokens for either user-delegated access or machine-to-machine authentication based on the configured OAuth 2.0 credential providers. The service will orchestrate the authentication process between the user or application to the downstream authorization server, and it will retrieve and store the resulting token. Once the token is available in the AgentCore Identity vault, authorized agents can retrieve it and use it to authorize calls to resource servers. For example, the sample code below will retrieve a token to interact with Google Drive on behalf of an end user. For more information, see [Integrate with Google Drive using OAuth2](identity-getting-started-google.md) for the complete example.

```
# Injects Google Access Token
@requires_access_token(
    # Uses the same credential provider name created above
    provider_name= "google-provider",
    # Requires Google OAuth2 scope to access Google Drive
    scopes= ["https://www.googleapis.com/auth/drive.metadata.readonly"],
    # Sets to OAuth 2.0 Authorization Code flow
    auth_flow= "USER_FEDERATION",
    # Prints authorization URL to console
    on_auth_url= lambda x: print("\nPlease copy and paste this URL in your browser:\n" + x),
    # If false, caches obtained access token
    force_authentication= False,
    callback_url='insert_oauth2_callback_url_for_session_binding',
)
async def write_to_google_drive(*, access_token: str):
    # Use the token to call Google Drive
    pass

# To invoke:
# asyncio.run(write_to_google_drive())
```

The process is similar to obtain a token for machine-to-machine calls, as shown in the following example:

```
import asyncio
from bedrock_agentcore.identity.auth import requires_access_token, requires_api_key

@requires_access_token(
    provider_name= "my-api-key-provider", # replace with your own credential provider name
    scopes= [],
    auth_flow= 'M2M',
)
async def need_token_2LO_async(*, access_token: str):
    # Use the access token
    pass

# To invoke:
# asyncio.run(need_token_2LO_async())
```

**Topics**
+ [

## Automatic refresh token storage and usage
](#automatic-refresh-token-storage)
+ [

## Streaming authorization URLs to application callers
](#authorization-url-streaming)
+ [

## Resource indicators in AgentCore OAuth2 flows
](#resource-indicators-cognito)

## Automatic refresh token storage and usage
<a name="automatic-refresh-token-storage"></a>

AgentCore automatically stores and uses refresh tokens when available from OAuth2 providers, reducing the frequency of user reauthorization prompts. When users initially grant consent through a standard OAuth2 authorization code flow, the system stores both access tokens and refresh tokens (if provided) in the secure token vault. This enables agents to obtain fresh access tokens automatically when the original tokens expire, improving user experience by minimizing repeated consent requests.

**Important**  
Access tokens returned by AgentCore are not guaranteed to be valid. Tokens can be revoked by customers on the federated provider side, which AgentCore cannot detect. If a token is invalid, use `forceAuthentication: true` to force a new authentication flow and obtain a valid access token.

Refresh tokens typically have longer lifespans than access tokens, with a default validity period of approximately 30 days compared to the shorter lifespan of access tokens (often 1-2 hours). When an access token expires, AgentCore automatically uses the stored refresh token to request a new access token from the provider. **If a valid refresh token is stored, AgentCore skips the user federation flow and directly returns a new access token** . If the refresh token is also expired or invalid, the system falls back to prompting the user for full reauthorization.

This feature requires no configuration within AgentCore - it operates automatically when refresh tokens are present in the OAuth2 provider’s token response. However, you must configure your OAuth2 provider to include refresh tokens in the authorization flow. The specific configuration depends on your provider:


| Provider | Configuration Required | 
| --- | --- | 
|   **Google**   |  Include `access_type=offline` in `customParameters` when calling `GetResourceOauth2Token`  <pre>"customParameters": { "access_type": "offline" }</pre>  | 
|   **Microsoft**   |  Include `offline_access` in `scopes` parameter when calling `GetResourceOauth2Token`  <pre>"scopes": ["openid", "profile", "offline_access"]</pre>  | 
|   **Salesforce**   |  Include `refresh_token` in `scopes` parameter when calling `GetResourceOauth2Token`  <pre>"scopes": ["api", "refresh_token"]</pre>  | 
|   **Atlassian**   |  Include `offline_access` in `scopes` parameter when calling `GetResourceOauth2Token`  <pre>"scopes": ["read:jira-user", "offline_access"]</pre>  | 
|   **GitHub**   |  No extra AgentCore configuration required. Enable User-to-server token expiration feature in your GitHub app settings. Refresh tokens are stored automatically when this feature is enabled.  | 
|   **Slack**   |  No extra AgentCore configuration required. Enable "token rotation" feature in your Slack app settings. Refresh tokens are returned automatically when this feature is enabled.  | 
|   **LinkedIn**   |  No extra AgentCore configuration required. Enable refresh token settings in your LinkedIn app configuration.  | 
|   **Other providers**   |  Some providers require configuration in their provider settings rather than API parameters. Consult your provider’s documentation for refresh token requirements.  | 

If your provider supports refresh tokens and is properly configured, AgentCore will automatically store and manage them without additional setup. To clear stored refresh tokens and force users to reauthenticate, set `forceAuthentication=true` when calling GetResourceOauth2Token. This clears the refresh token and forces a complete federation flow. For information about configuring OAuth2 providers, see [Provider setup and configuration](identity-idps.md).

## Streaming authorization URLs to application callers
<a name="authorization-url-streaming"></a>

For three-legged OAuth (3LO) flows, your agent needs to provide the authorization URL to the calling application so users can complete the consent flow. While the examples above show printing the URL to the console, production applications require streaming the URL back to the caller through your application’s response mechanism.

 **Common implementation patterns** 

 **Streaming response pattern** – For applications that support streaming responses, you can send the authorization URL as part of the response stream:

```
import asyncio
from bedrock_agentcore.identity.auth import requires_access_token

@requires_access_token(
    provider_name="google-provider",
    scopes=["https://www.googleapis.com/auth/drive.metadata.readonly"],
    auth_flow="USER_FEDERATION",
    # Stream URL back to caller instead of printing
    on_auth_url=lambda url: stream_to_caller({
        "type": "authorization_required",
        "authorization_url": url,
        "message": "Please visit this URL to authorize access"
    }),
    force_authentication=False,
    callback_url='insert_oauth2_callback_url_for_session_binding'
)
async def agent_with_streaming_auth(*, access_token: str):
    # Agent logic continues after user completes authorization
    return {"status": "success", "token_received": True}

def stream_to_caller(data):
    # Implementation depends on your streaming mechanism
    # Examples: WebSocket, Server-Sent Events, HTTP chunked response
    response_stream.send(json.dumps(data))
```

 **Callback pattern** – For applications using callbacks or webhooks, store the authorization URL and notify the caller:

```
import asyncio
from bedrock_agentcore.identity.auth import requires_access_token

@requires_access_token(
    provider_name="google-provider",
    scopes=["https://www.googleapis.com/auth/drive.metadata.readonly"],
    auth_flow="USER_FEDERATION",
    # Store URL and trigger callback
    on_auth_url=lambda url: handle_auth_callback(url),
    force_authentication=False,
    callback_url='insert_oauth2_callback_url_for_session_binding'
)
async def agent_with_callback_auth(*, access_token: str):
    return {"status": "success", "data": "processed"}

def handle_auth_callback(authorization_url):
    # Store the URL associated with the request
    auth_store.save(request_id, {
        "authorization_url": authorization_url,
        "status": "pending_authorization"
    })

    # Notify the calling application
    callback_service.notify(callback_url, {
        "request_id": request_id,
        "authorization_url": authorization_url,
        "action_required": "user_authorization"
    })
```

 **Polling pattern** – For applications that prefer polling, store the authorization URL in a retrievable location:

```
import asyncio
from bedrock_agentcore.identity.auth import requires_access_token

@requires_access_token(
    provider_name="google-provider",
    scopes=["https://www.googleapis.com/auth/drive.metadata.readonly"],
    auth_flow="USER_FEDERATION",
    # Store URL for polling retrieval
    on_auth_url=lambda url: store_auth_url_for_polling(url),
    force_authentication=False,
    callback_url='insert_oauth2_callback_url_for_session_binding'
)
async def agent_with_polling_auth(*, access_token: str):
    return {"status": "success", "data": "processed"}

def store_auth_url_for_polling(authorization_url):
    # Store in database, cache, or session store
    session_store.set(f"auth_url:{session_id}", {
        "authorization_url": authorization_url,
        "created_at": datetime.utcnow(),
        "status": "pending"
    }, ttl=300)  # 5 minute expiration
```

Choose the pattern that best fits your application architecture. Streaming responses provide the best user experience for real-time applications, while callback and polling patterns work well for asynchronous or batch processing scenarios.

## Resource indicators in AgentCore OAuth2 flows
<a name="resource-indicators-cognito"></a>

Resource indicators provide a standardized way to specify which resource server should accept an OAuth2 access token. AgentCore uses Cognito as its authentication provider, which supports RFC 8707-compliant resource indicators that allow you to specify the intended resource server during token requests. To use resource indicators, you must first configure the authorization server to recognize specific resource servers using Cognito’s CreateResourceServer API. Once configured, when you specify a resource indicator in your token request, Cognito includes the corresponding resource server identifier in the aud claim of the resulting token, enabling the resource server to verify that the token is intended for its specific use. This provides several important benefits: resource servers can validate that tokens are specifically intended for them (principle of least privilege), improved auditability by clearly identifying which resource server each token targets, and reduced risk of token misuse across different services within your application environment.

Through Cognito’s [RFC 8707](https://www.rfc-editor.org/rfc/rfc8707.html) implementation, AgentCore enables clients to specify a resource server directly in authorization and token requests, overriding the default audience parameter. In Cognito, the 'resource indicator' referred to in the RFC corresponds to the [ResourceServer’s](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateResourceServer.html) 'identifier' value. Resource indicators are particularly important for Model Context Protocol (MCP) implementations, where they help mitigate specific security risks outlined in the MCP authorization specification. The resource indicator corresponds to the RFC 9728 resource parameter, ensuring proper token scoping for MCP server interactions. Note that the current implementation supports single-resource binding, meaning you can specify one resource server per token request.

Use resource indicators when your agents need to access resource servers with specific security requirements, or when you need fine-grained control over token audience validation. Resource indicators are particularly useful for multi-tenant applications where tokens should be restricted to specific customer resources.

# OAuth 2.0 authorization URL session binding
<a name="oauth2-authorization-url-session-binding"></a>

AgentCore Identity provides OAuth 2.0 access token retrievals for your agent applications to access third-party application vendors or resources protected by identity providers / authorization servers. If an application or a resource requires a user to authorize explicitly with an OAuth authorization code flow, AgentCore Identity generates an authorization URL for the user to navigate to and consent access. Then, upon user giving consent, AgentCore Identity fetches the access token from the application or resource on behalf of users, and stores it in the AgentCore Identity Token Vault.

However, since a user may accidentally send the authorization URL to another user and gain access to that user’s application or resource, your application must verify that the user who initiates an authorization request is still the same as the user who has granted consent to the application or resource. To do that, you need to register a publicly available HTTPS application endpoint with AgentCore Identity that handles user verification.

## How session binding works
<a name="how-session-binding-works"></a>

The following flow diagram and corresponding steps show the OAuth 2.0 authorization URL session binding process:

![\[OAuth 2.0 authorization URL session binding flow diagram\]](http://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/images/identity-session-binding.png)


1.  **Invoke agent** – Your agent code invokes `GetResourceOauth2Token` API to retrieve an authorization URL, when an originating agent user wants to access some application or resource that he/she owns.

1.  **Generate authorization URL** – AgentCore Identity generates an authorization URL and session URI for the user to navigate to and consent access.

1.  **Authorize and obtain access token** – The user navigates to the authorization URL and grants consent for your agent to access his/her resource. After that, AgentCore Identity redirects the user’s browser to your HTTPS application endpoint with information containing the originating user of the authorization request. At this point, your HTTPS application endpoint determines if the originating agent user is still the same as the currently logged in user of your application. If they match, your application endpoint invokes `CompleteResourceTokenAuth` so that AgentCore Identity can fetch and store the access token.

1.  **Re-invoke agent to obtain access token** – Once the application returns a valid response, your agent application will be able to retrieve the OAuth2.0 access tokens that were originally requested for the user. If the users do not match, your application simply does nothing or logs the attempt.

By allowing your application endpoint to verify the user identity, AgentCore Identity allows your agent application to ensure that it is always the same user who initiated the authorization request and the one who consented access.

## Implementation details
<a name="implementation-details"></a>

The following steps walk you through setting up the workload identity, the OAuth 2.0 credential provider, and the OAuth 2.0 application client from the resource provider for retrieving an OAuth 2.0 access token for your agent application.

You can refer to sample code as an example of a working application: [OAuth 2.0 callback server implementation](https://github.com/awslabs/amazon-bedrock-agentcore-samples/blob/main/01-tutorials/03-AgentCore-identity/05-Outbound_Auth_3lo/oauth2_callback_server.py).

**Important**  
When you are using the AgentCore CLI with `agentcore dev` in a local environment, to simplify your local development and testing, the CLI hosts the callback endpoint and calls the `CompleteResourceTokenAuth` API on your behalf to verify the user session to get OAuth 2.0 access tokens so you can skip steps 1, 2 and 4 in the following setup. However, when deploying your agent code to AgentCore Runtime, your web application that connects to the agent runtime must host a publicly accessible HTTPS callback endpoint itself, the callback endpoint must be registered against the workload identity as an `AllowedResourceOAuth2ReturnUrl` by calling `UpdateWorkloadIdentity` using the agent ID provided by AgentCore Runtime, and then call the `CompleteResourceTokenAuth` API after verifying the current user’s browser session to secure your OAuth 2.0 authorization flows.

 **To implement OAuth 2.0 authorization URL session binding** 

1.  **Create an application URL** – For your user-facing browser application, create and host a new URL that is accessible from the user browser and can accept requests from browser redirects. This page should either redirect to an application page that your user can continue with their agent session OR render some basic web page instructing your users to return their currently active agent session. In later parts of the implementation, this page is used for validation of the current user’s active session, so this page should also be able to access and maintain your application user session data.

   As an example, your application may have its users interact with an agent at a primary application page like `https://myagentapp.com/assistant` . You’ll want to expose a new URL like `https://myagentapp.com/callback` that for now will redirect to the primary application page. The actual code logic in your `/callback` endpoint will be updated later when following this guide.

1.  **Update workload identity with application URL** – (Can be skipped if testing locally via AgentCore CLI) Once you have created and hosted an application URL for AgentCore Identity to redirect to, update your workload identity so that the application URL is registered as an `AllowedResourceOauth2ReturnUrl` . Make sure that the IAM credentials used have permissions to call `CreateWorkloadIdentity` or `UpdateWorkloadIdentity` depending on whether you’re creating a new workload identity or updating an existing one.
**Note**  
For workload identities created on your behalf by AgentCore Runtime or Gateway, the workload identity name will correspond to the runtime ID or gateway ID that is issued by the services.

   Sample `UpdateWorkloadIdentity` API call:

   ```
   aws bedrock-agentcore-control update-workload-identity --name GoogleCalendarAgent \
   --allowed-resource-oauth2-return-urls https://myagentapp.com/callback
   ```

1.  **Create OAuth 2.0 credential provider in AgentCore Identity** – To register the OAuth 2.0 credential provider fully, you need permissions to call `CreateOauth2CredentialProvider` and `UpdateOauth2CredentialProvider` . Follow these steps:
   + Call `CreateOauth2CredentialProvider` with placeholders for client ID and client secret.
   + API response will contain an OAuth callback (redirect) URL like: `https://bedrock-agentcore.amazonaws.com/identities/callback/123-456-7890` 

     Record this value as it’s specific for each provider that is created and will be needed later by the OAuth 2.0 resource provider.
   + Go to your resource provider (for example, Google or GitHub) and create an OAuth 2.0 application client. Provide the callback URL issued by the service from the `CreateOauth2CredentialProvider` call to the resource provider as an allowed OAuth 2.0 callback URL.
   + Once the OAuth 2.0 application client has been created, record the client ID and client secret assigned to your app client as you need to update the OAuth 2.0 Credential Provider with these values.
   + Call `UpdateOauth2CredentialProvider` and provide the client ID and client secret provided by the resource provider, replacing the placeholder values that were provided when creating the credential provider.

1.  **Add code handler for calling CompleteResourceTokenAuth** – Once you have created your OAuth 2.0 credential provider, add code and the IAM permissions to call the `CompleteResourceTokenAuth` API in your application URL handler. When calling the `CompleteResourceTokenAuth` API, your application must present the original inbound identity provider OAuth token or `user_id` String that was used to generate the workload access token to represent the user and the agent application involved in the OAuth 2.0 authorization flow. This information should be fetched from the active application session on the user’s browser (typically through a browser cookie or in browser local storage) and should NOT be pulled from any remote session cache.

   Additionally, each authorization URL that gets generated by AgentCore Identity is uniquely identified with its own session URI. This session URI must also be presented alongside the user identifier to bind the session with the intended user.
**Important**  
Prior to your application calling the `CompleteResourceTokenAuth` API, your application must verify that the current user has an active, valid session with your application. By doing so your application can associate the intended user with the Authorization session. Furthermore, if you have a backend service that your application depends on, you can move the code that calls `CompleteResourceTokenAuth` API to your backend, and have your application forward the inbound identity provider OAuth token or `user_id` to your backend.

   Sample application code:

   ```
   def _handle_3lo_callback(self, request: Request) -> JSONResponse:
       session_id = request.query_params.get("session_id")
   
       if not session_id:
           console.print("Missing session_id in OAuth2 3LO callback")
           return JSONResponse(status_code=400, content={"message": "missing session_id query parameter"})
   
       session_details = validate_session_cookies(request.cookies.get('my-application-cookie'))
   
       user_id = None
       if oauth2_config:
           user_id = session_details.get(USER_ID)
   
       if not user_id:
           console.print(f"Missing {USER_ID} in session_details")
           return JSONResponse(status_code=500, content={"message": "Internal Server Error"})
   
       console.print(f"Handling 3LO callback for workload_user_id={user_id} | session_id={session_id}", soft_wrap=True)
   
       region = agent_config.aws.region
       if not region:
           console.print("AWS Region not configured")
           return JSONResponse(status_code=500, content={"message": "Internal Server Error"})
   
       identity_client = IdentityClient(region)
       identity_client.complete_resource_token_auth(
           session_uri=session_id, user_identifier=UserIdIdentifier(user_id=user_id)
       )
   
       return JSONResponse(status_code=200, content={"message": "OAuth2 3LO flow completed successfully"})
   ```

1.  **Test** – Once you have completed the setup, you are ready to test the integration. Start by calling `GetResourceOauth2Token` and in your browser go to the Authorization URL that is returned. After completing the authorization at the OAuth 2.0 resource provider, you should see the browser redirect back to your application URL and invoke the `CompleteResourceTokenAuth` API. Once the application returns a valid response, your agent application will be able to retrieve the OAuth 2.0 access tokens that were originally requested for the user. These tokens can be fetched by calling the `GetResourceOauth2Token` API.

## Additional considerations
<a name="additional-considerations"></a>

When implementing OAuth 2.0 authorization URL session binding, keep the following considerations in mind:
+ Each authorization URL and its corresponding session identifier are only valid for 10 minutes.
+ To secure your application callback endpoint against CSRF attacks, we highly recommend that you generate an opaque state to include in your API call to `GetResourceOAuth2Token` . Your application should be able to parse this value to ensure it’s serving requests that were initiated by your agent application.

# Scope down access to credential providers by workload identity
<a name="scope-credential-provider-access"></a>

You can use IAM policies to control which workload identities have access to specific credential providers. This enables fine-grained access control, ensuring that only authorized agents can retrieve credentials for particular services.

 **Access control mechanisms** 
+  **Workload identity-based restrictions** – Limit credential provider access to specific workload identities
+  **Resource-level permissions** – Control access to individual credential providers using ARN-based policies
+  **Directory-level controls** – Manage access at the workload identity directory level

**Topics**
+ [

## IAM policy examples
](#iam-policy-examples)
+ [

## Implementation steps
](#policy-implementation-steps)

## IAM policy examples
<a name="iam-policy-examples"></a>

The following examples demonstrate how to create IAM policies that restrict credential provider access based on workload identity:

 **Restrict API key provider access** 

```
{
"Version": "2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "GetResourceApiKey",
      "Effect": "Allow",
      "Action": [
        "bedrock-agentcore:GetResourceApiKey"
      ],
      "Resource": [
        "arn:aws:bedrock-agentcore:us-east-1:<account_id>:workload-identity-directory/default",
        "arn:aws:bedrock-agentcore:us-east-1:<account_id>:workload-identity-directory/default/workload-identity/<workload-identity-name>",
        "arn:aws:bedrock-agentcore:us-east-1:<account_id>:token-vault/default"
      ]
    }
  ]
}
```

 **Restrict OAuth2 credential provider access** 

```
{
"Version": "2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "GetResourceOauth2Token",
      "Effect": "Allow",
      "Action": [
        "bedrock-agentcore:GetResourceOauth2Token"
      ],
      "Resource": [
        "arn:aws:bedrock-agentcore:us-east-1:<account_id>:workload-identity-directory/default",
        "arn:aws:bedrock-agentcore:us-east-1:<account_id>:workload-identity-directory/default/workload-identity/<workload-identity-name>",
        "arn:aws:bedrock-agentcore:us-east-1:<account_id>:token-vault/default"
      ]
    }
  ]
}
```

 **Allow multiple workload identities access to a credential provider** 

```
{
"Version": "2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "GetResourceApiKeyMultipleIdentities",
      "Effect": "Allow",
      "Action": [
        "bedrock-agentcore:GetResourceApiKey"
      ],
      "Resource": [
        "arn:aws:bedrock-agentcore:us-east-1:<account_id>:workload-identity-directory/default",
        "arn:aws:bedrock-agentcore:us-east-1:<account_id>:workload-identity-directory/default/workload-identity/agent-1",
        "arn:aws:bedrock-agentcore:us-east-1:<account_id>:workload-identity-directory/default/workload-identity/agent-2",
        "arn:aws:bedrock-agentcore:us-east-1:<account_id>:workload-identity-directory/default/workload-identity/agent-3",
        "arn:aws:bedrock-agentcore:us-east-1:<account_id>:token-vault/default"
      ]
    }
  ]
}
```

## Implementation steps
<a name="policy-implementation-steps"></a>

To implement workload identity-based access control for credential providers:

1.  **Identify your workload identities** – Use `aws bedrock-agentcore-control list-workload-identities` to list all workload identities in your account. For information about creating and managing workload identities, see [Manage workload identities with AgentCore Identity](identity-manage-agent-ids.md).

1.  **Determine credential provider ARNs** – Identify the specific credential providers you want to control access to

1.  **Create IAM policies** – Write IAM policies that specify which workload identities can access which credential providers

1.  **Attach policies to roles** – Attach the policies to the IAM roles used by your agents or applications

1.  **Test access controls** – Verify that only authorized workload identities can access the specified credential providers

 **Best practices** 
+ Use descriptive names for workload identities to make policy management easier
+ Regularly audit and review access policies to ensure they align with your security requirements
+ Consider using IAM policy conditions for additional access controls based on time, IP address, or other factors
+ Test policies in a development environment before applying them to production workloads

# Obtain API key
<a name="obtain-api-key"></a>

Once you have stored your API keys in the AgentCore Identity vault, you can retrieve them directly in your agent using the AgentCore SDK and the `@requires_api_key` annotation. For example, the code below will retrieve the API key from the “your-service-name” API key provider so that you can use it in the `need_api_key` function.

```
import asyncio
from bedrock_agentcore.identity.auth import requires_api_key

@requires_api_key(
    provider_name= "your-service-name" # replace with your own credential provider name
)
async def need_api_key(*, api_key: str):
    # Use the API key
    pass

# To invoke:
# asyncio.run(need_api_key())
```

# Provider setup and configuration
<a name="identity-idps"></a>

Amazon Bedrock AgentCore Identity provides managed OAuth 2.0 supported providers for both inbound and outbound authentication. Each provider encapsulates the specific authentication protocols, endpoint configurations, and credential formats required for a particular service or identity system. The service provides built-in providers for popular services including Google, GitHub, Slack, and Salesforce with authorization server endpoints and provider-specific parameters pre-configured to reduce development effort. The providers abstract away the complexity of different OAuth 2.0 implementations, API authentication schemes, and token formats, presenting a unified interface to agents while handling the underlying protocol variations and edge cases.

Built-in providers are maintained by the AgentCore Identity team and automatically updated to handle changes in external service APIs, security requirements, and best practices.

Supported providers include:

**Topics**
+ [

# Amazon Cognito
](identity-idp-cognito.md)
+ [

# Auth0 by Okta
](identity-idp-auth0.md)
+ [

# Atlassian
](identity-idp-atlassian.md)
+ [

# CyberArk
](identity-idp-cyberark.md)
+ [

# Dropbox
](identity-idp-dropbox.md)
+ [

# Facebook
](identity-idp-facebook.md)
+ [

# FusionAuth
](identity-idp-fusionauth.md)
+ [

# GitHub
](identity-idp-github.md)
+ [

# Google
](identity-idp-google.md)
+ [

# HubSpot
](identity-idp-hubspot.md)
+ [

# LinkedIn
](identity-idp-linkedin.md)
+ [

# Microsoft
](identity-idp-microsoft.md)
+ [

# Notion
](identity-idp-notion.md)
+ [

# Okta
](identity-idp-okta.md)
+ [

# OneLogin
](identity-idp-onelogin.md)
+ [

# Ping Identity
](identity-idp-pingidentity.md)
+ [

# Reddit
](identity-idp-reddit.md)
+ [

# Salesforce
](identity-idp-salesforce.md)
+ [

# Slack
](identity-idp-slack.md)
+ [

# Spotify
](identity-idp-spotify.md)
+ [

# Twitch
](identity-idp-twitch.md)
+ [

# X
](identity-idp-x.md)
+ [

# Yandex
](identity-idp-yandex.md)
+ [

# Zoom
](identity-idp-zoom.md)

# Amazon Cognito
<a name="identity-idp-cognito"></a>

Amazon Cognito can be configured as an identity provider for accessing AgentCore Gateway and Runtime, or an AgentCore Identity credential provider for outbound resource access. This allows your agents to authenticate and authorize agent users with Cognito as the identity provider and authorization server, or your agents to obtain credentials to access resources authorized by Cognito.

## Inbound
<a name="identity-idp-cognito-inbound"></a>

To add Cognito as an identity provider and authorization server for accessing AgentCore Gateway and Runtime, you must:
+ Configure discovery URL from your IDP directory. This helps AgentCore Identity get the metadata related to your OAuth authorization server and token verification keys.
+ Enter valid `clientId` or `aud` claims for the token. This helps validate the tokens coming from your IDP and allow access for tokens that contain expected claims.

Use the following procedure to create a Cognito user pool as an inbound identity provider for user authentication with AgentCore Runtime. The following steps will create a Cognito user pool, a user pool client, add a user, and generate a bearer token for the user. The token is valid for 60 minutes by default.

 **To create a Cognito user pool as an inbound identity provider for Runtime authentication** 

1. Create a file named `setup_cognito.sh` with the following content:
**Note**  
The following script is only meant as an example. You should customize the user pool settings and user credentials as needed for your application. Do not use this script directly in production environments.

   ```
   #!/bin/bash
   
   # Create User Pool and capture Pool ID directly
   export POOL_ID=$(aws cognito-idp create-user-pool \
     --pool-name "MyUserPool" \
     --policies '{"PasswordPolicy":{"MinimumLength":8}}' \
     --region us-east-1 | jq -r '.UserPool.Id')
   
   # Create App Client and capture Client ID directly
   export CLIENT_ID=$(aws cognito-idp create-user-pool-client \
     --user-pool-id $POOL_ID \
     --client-name "MyClient" \
     --no-generate-secret \
     --explicit-auth-flows "ALLOW_USER_PASSWORD_AUTH" "ALLOW_REFRESH_TOKEN_AUTH" \
     --region us-east-1 | jq -r '.UserPoolClient.ClientId')
   
   # Create User
   aws cognito-idp admin-create-user \
     --user-pool-id $POOL_ID \
     --username "testuser" \
     --temporary-password "${temp-password}" \
     --region us-east-1 \
     --message-action SUPPRESS > /dev/null
   
   # Set Permanent Password
   aws cognito-idp admin-set-user-password \
     --user-pool-id $POOL_ID \
     --username "testuser" \
     --password "${permanent-user-password}" \
     --region us-east-1 \
     --permanent > /dev/null
   
   # Authenticate User and capture Access Token
   export BEARER_TOKEN=$(aws cognito-idp initiate-auth \
     --client-id "$CLIENT_ID" \
     --auth-flow USER_PASSWORD_AUTH \
     --auth-parameters USERNAME='testuser',PASSWORD='${permanent-user-password}' \
     --region us-east-1 | jq -r '.AuthenticationResult.AccessToken')
   
   # Output the required values
   echo "Pool id: $POOL_ID"
   echo "Discovery URL: https://cognito-idp.us-east-1.amazonaws.com/$POOL_ID/.well-known/openid-configuration"
   echo "Client ID: $CLIENT_ID"
   echo "Bearer Token: $BEARER_TOKEN"
   ```

1. Run the script to create the Cognito resources:

   ```
   source setup_cognito.sh
   ```

1. Record the output values, which will look similar to:

   ```
   Pool id: us-east-1_poolid
   Discovery URL: https://cognito-idp.us-east-1.amazonaws.com/us-east-1_userpoolid/.well-known/openid-configuration
   Client ID: clientid
   Bearer Token: bearertoken
   ```

   You’ll need these values in the next steps.

Use the following procedure to create a Cognito user pool as an inbound identity provider for machine-to-machine authentication with AgentCore Gateway. The following steps will create a user pool, resource server, client credentials, and discovery URL configuration. This setup enables M2M authentication flows for Gateway access.

 **To create a Cognito user pool as an inbound identity provider for Gateway authentication** 

1. Create a user pool:

   ```
   aws cognito-idp create-user-pool \
     --region us-west-2 \
     --pool-name "gateway-user-pool"
   ```

1. Record the user pool ID from the response or retrieve it using:

   ```
   aws cognito-idp list-user-pools \
     --region us-west-2 \
     --max-results 60
   ```

1. Create a resource server for the user pool:

   ```
   aws cognito-idp create-resource-server \
     --region us-west-2 \
     --user-pool-id <UserPoolId> \
     --identifier "gateway-resource-server" \
     --name "GatewayResourceServer" \
     --scopes '[{"ScopeName":"read","ScopeDescription":"Read access"}, {"ScopeName":"write","ScopeDescription":"Write access"}]'
   ```

1. Create a client for the user pool:

   ```
   aws cognito-idp create-user-pool-client \
     --region us-west-2 \
     --user-pool-id <UserPoolId> \
     --client-name "gateway-client" \
     --generate-secret \
     --allowed-o-auth-flows client_credentials \
     --allowed-o-auth-scopes "gateway-resource-server/read" "gateway-resource-server/write" \
     --allowed-o-auth-flows-user-pool-client \
     --supported-identity-providers "COGNITO"
   ```

   Record the client ID and client secret from the response. You’ll need these values to configure the Cognito provider in AgentCore Identity.

1. If needed, create a domain for your user pool:

   ```
   aws cognito-idp create-user-pool-domain \
     --domain <UserPoolIdWithoutUnderscore> \
     --user-pool-id <UserPoolId> \
     --region us-west-2
   ```
**Note**  
Remove any underscore from the `UserPoolId` when creating the domain. For example, if your user pool ID is "us-west-2\$1gmSGKKGr9", use "us-west-2gmSGKKGr9" as the domain.

1. Construct the discovery URL for your Cognito user pool:

   ```
   https://cognito-idp.us-west-2.amazonaws.com/<UserPoolId>/.well-known/openid-configuration
   ```

1. Configure the Gateway Inbound Auth with the following values:

   1.  **Discovery URL** : The URL constructed in the previous step

   1.  **Allowed clients** : The client ID obtained when creating the user pool client

## Outbound
<a name="identity-idp-cognito-outbound"></a>

To configure Cognito user pools as an outbound resource provider, use the following configuration:

```
{
  "name": "Cognito",
  "credentialProviderVendor": "CognitoOauth2",
  "oauth2ProviderConfigInput" : {
    "includedOauth2ProviderConfig": {
      "clientId": "your-client-id",
      "clientSecret": "your-client-secret",
      "authorizationEndpoint": "https://{your-cognito-domain}.auth.us-east-1.amazoncognito.com/oauth2/authorize",
      "tokenEndpoint": "https://{your-cognito-domain}.auth.us-east-1.amazoncognito.com/oauth2/token",
      "issuer": "https://cognito-idp.us-east-1.amazonaws.com/{your-user-pool-id}"
    }
  }
}
```

# Auth0 by Okta
<a name="identity-idp-auth0"></a>

Auth0 can be configured as an identity provider for accessing AgentCore Gateway and Runtime, or an AgentCore Identity credential provider for outbound resource access. This allows your agents to authenticate and authorize agent users with Auth0 as the identity provider and authorization server, or your agents to obtain credentials to access resources authorized by Auth0.

## Inbound
<a name="identity-idp-auth0-inbound"></a>

To add Auth0 as an identity provider and authorization server for accessing AgentCore Gateway and Runtime, you must:
+ Configure discovery URL from your IDP directory. This helps AgentCore Identity get the metadata related to your OAuth authorization server and token verification keys.
+ Enter valid `aud` claims for the token. This helps validate the tokens coming from your IDP and allows access for tokens that contain expected claims.

Use the following procedure to set up Auth0 and obtain the necessary configuration values for Gateway authentication.

 **To configure Auth0 for inbound authentication** 

1. Create an API in Auth0:

   1. Sign in to your Auth0 dashboard.

   1. Open **APIs** and choose **Create API**.

   1. Enter a name and identifier for your API (e.g., "gateway-api").

   1. Select the signing algorithm (RS256 recommended).

   1. Choose **Create**.

1. Configure API scopes:

   1. In the API settings, go to the **Scopes** tab.

   1. Add scopes such as "invoke:gateway" and "read:gateway".

1. Create an application:

   1. Open **Applications** and choose **Create Application**.

   1. Select **Machine to Machine Application**.

   1. Select the API you created in step 1.

   1. Authorize the application for the scopes you created.

   1. Choose **Create**.

1. Record the client ID and client secret from the application settings. You’ll need these values to configure the Auth0 provider in AgentCore Identity.

1. Construct the discovery URL for your Auth0 tenant:

   ```
   https://your-domain/.well-known/openid-configuration
   ```

   Where *your-domain* is your Auth0 tenant domain (e.g., "dev-example.us.auth0.com").

1. Configure Inbound Auth with the following values:

   1.  **Discovery URL** : The URL constructed in the previous step

   1.  **Allowed audiences** : The API identifier you created in step 1

## Outbound
<a name="identity-idp-auth0-outbound"></a>

To configure Auth0 as an outbound resource provider, use the following:

```
{
  "name": "NAME",
  "credentialProviderVendor": "Auth0Oauth2",
  "oauth2ProviderConfigInput" : {
    "includedOauth2ProviderConfig": {
      "clientId": "your-client-id",
      "clientSecret": "your-client-secret",
      "authorizationEndpoint": "https://your-auth0-tenant.auth0.com/authorize",
      "tokenEndpoint": "https://your-auth0-tenant.auth0.com/oauth/token",
      "issuer": "https://your-auth0-tenant.auth0.com"
    }
  }
}
```

# Atlassian
<a name="identity-idp-atlassian"></a>

Atlassian can be configured as an AgentCore Identity credential provider for outbound resource access. This allows your agents to authenticate users through Atlassian’s OAuth2 service and obtain access tokens for Atlassian API resources.

## Outbound
<a name="identity-idp-atlassian-outbound"></a>

 **Step 1** 

Use the following procedure to set up an Atlassian OAuth2 application and obtain the necessary client credentials for AgentCore Identity.

 **To configure an Atlassian OAuth2 application** 

1. Open Atlassian’s developer console and register for a developer account.

1. Create a new application.

1. Select authorization and next to **OAuth 2.0 (3LO)** select **Configure**.

1. Enter the following as a callback URL for the app:

   ```
   https://bedrock-agentcore.region.amazonaws.com/identities/oauth2/callback
   ```

1. Choose **Save changes**.

1. Select **Permissions** and choose the permissions relevant to your application.

For more details, refer to [Atlassian’s OAuth 2.0 (3LO) apps documentation](https://developer.atlassian.com/cloud/confluence/oauth-2-3lo-apps/).

 **Step 2** 

To configure Atlassian as an outbound resource provider, use the following:

```
{
   "name": "NAME",
   "credentialProviderVendor": "AtlassianOAuth2",
   "oauth2ProviderConfigInput": {
       "atlassianOauth2ProviderConfig": {
           "clientId": "your-client-id",
           "clientSecret": "your-client-secret"
       }
   }
}
```

# CyberArk
<a name="identity-idp-cyberark"></a>

CyberArk can be configured as an AgentCore Identity credential provider for outbound resource access. This allows your agents to authenticate users through CyberArk’s OAuth2 service and obtain access tokens for CyberArk API resources.

## Outbound
<a name="identity-idp-cyberark-outbound"></a>

 **Step 1** 

Use the following procedure to set up a CyberArk OpenID Connect application and obtain the necessary client credentials for AgentCore Identity.

 **To configure a CyberArk OAuth2 application** 

1. Open the developer console for CyberArk.

1. Open **Identity Administration** and then choose **Web Apps**.

1. Open the **Custom** tab.

1. Create a custom **OpenID Connect** application.

1. Open the **Trust** page, and use the following in the **Authorized Redirect URIs** :

   ```
   https://bedrock-agentcore.region.amazonaws.com/identities/oauth2/callback
   ```

1. Record the client ID and client secret generated as you’ll need this information to configure the CyberArk resource provider in AgentCore Identity.

1. Configure any scopes necessary for your application.

1. Deploy the application by setting the appropriate permissions by opening the **Permissions** page and adding the relevant permissions.

For more details, refer to [CyberArk’s OpenID Connect documentation](https://docs.cyberark.com/identity/latest/en/content/applications/appscustom/openidaddconfigapp.htm).

 **Step 2** 

To configure CyberArk as an outbound resource provider, use the following:

```
{
  "name": "CyberArk",
  "credentialProviderVendor": "CyberArkOauth2",
  "oauth2ProviderConfigInput" : {
    "includedOauth2ProviderConfig": {
      "clientId": "your-client-id",
      "clientSecret": "your-client-secret",
      "authorizationEndpoint": "https://your-tenant-id.id.cyberark.cloud/OAuth2/Authorize/__idaptive_cybr_user_oidc",
      "tokenEndpoint": "https://your-tenant-id.id.cyberark.cloud/OAuth2/Token/__idaptive_cybr_user_oidc",
      "issuer": "https://your-tenant-id.id.cyberark.cloud/__idaptive_cybr_user_oidc"
    }
  }
}
```

# Dropbox
<a name="identity-idp-dropbox"></a>

Dropbox can be configured as an AgentCore Identity credential provider for outbound resource access. This allows your agents to authenticate users through Dropbox’s OAuth2 service and obtain access tokens for Dropbox API resources.

**Note**  
Dropbox does not support the M2M/Client Credentials flow.

## Outbound
<a name="identity-idp-dropbox-outbound"></a>

 **Step 1** 

Use the following procedure to set up a Dropbox OAuth2 application and obtain the necessary client credentials for AgentCore Identity.

 **To configure a Dropbox OAuth2 application** 

1. Open the developer **App Console** for Dropbox.

1. Choose **Create app**.

1. Choose **Scoped access**.

1. For the access type, choose the access type appropriate for your application.

1. Provide a name for your application.

1. Choose **Create app**.

1. On the app overview page, open the OAuth2 section and add the following as a redirect URI:

   ```
   https://bedrock-agentcore.region.amazonaws.com/identities/oauth2/callback
   ```

1. In the same section choose the dropdown below **Allow public clients (Implicit Grant & PKCE)** and choose **Disallow** in the options.

1. Record the app key and app secret as you’ll need the information to configure the Dropbox resource provider in AgentCore Identity.

1. In the **Permissions** tab for the application, select the scopes that are needed for your application.

For more details, refer to [Dropbox’s OAuth implementation guide](https://developers.dropbox.com/oauth-guide#implementing-oauth).

 **Step 2** 

To configure Dropbox as an outbound resource provider, use the following:

```
{
  "name": "DropBox",
  "credentialProviderVendor": "DropboxOauth2",
  "oauth2ProviderConfigInput" : {
    "includedOauth2ProviderConfig": {
      "clientId": "your-client-id",
      "clientSecret": "your-client-secret"
    }
  }
}
```

# Facebook
<a name="identity-idp-facebook"></a>

Facebook can be configured as an AgentCore Identity credential provider for outbound resource access. This allows your agents to authenticate users through Facebook’s OAuth2 service and obtain access tokens for Facebook API resources.

## Outbound
<a name="identity-idp-facebook-outbound"></a>

 **Step 1** 

Use the following procedure to set up a Facebook OAuth2 application and obtain the necessary client credentials for AgentCore Identity.

 **To configure a Facebook OAuth2 application** 

1. Create a [developer account with Facebook](https://developers.facebook.com/docs/facebook-login).

1.  [Sign in](https://developers.facebook.com/) with your Facebook credentials.

1. From the **My Apps** menu, choose **Create New App**.
**Note**  
If you don’t have an existing Facebook app, you will see a different option. Choose **Create App**.

1. On the **Create an app** page, choose a use case for your app, and then choose **Next**.

1. Enter a name for your Facebook app and choose **Create App**.

1. On the left navigation bar, choose **App Settings** , and then choose **Basic**.

1. Record the **App ID** and the **App Secret** . You will use them for configuring the Facebook provider in AgentCore Identity.

1. Choose **\$1 Add platform** from the bottom of the page.

1. On the **Select Platform** screen, select your platforms, and then choose **Next**.

1. Choose **Save changes**.

1. For **App Domains** , enter the domain of your application and `bedrock-agentcore.region.amazonaws.com`.

1. Choose **Save changes**.

1. From the navigation bar, choose **Products** , and then choose **Configure** from **Facebook Login**.

1. From the **Facebook Login** **Configure** menu, choose **Settings**.

1. Enter the following redirect URL into **Valid OAuth Redirect URIs** :

   ```
   https://bedrock-agentcore.region.amazonaws.com/identities/oauth2/callback
   ```

1. Choose **Save changes**.

 **Step 2** 

To configure Facebook as an outbound resource provider, use the following:

```
{
  "name": "Facebook",
  "credentialProviderVendor": "FacebookOauth2",
  "oauth2ProviderConfigInput" : {
    "includedOauth2ProviderConfig": {
      "clientId": "your-client-id",
      "clientSecret": "your-client-secret"
    }
  }
}
```

# FusionAuth
<a name="identity-idp-fusionauth"></a>

FusionAuth can be configured as an outbound resource credential provider for AgentCore Identity. This allows your agents to authenticate users through FusionAuth’s OAuth2 service and obtain access tokens for FusionAuth API resources.

## Outbound
<a name="identity-idp-fusionauth-outbound"></a>

 **Step 1** 

Use the following procedure to set up a FusionAuth OAuth2 application and obtain the necessary client credentials for AgentCore Identity.

 **To configure a FusionAuth OAuth2 application** 

1. Open the developer console for FusionAuth.

1. In the main navigation bar, choose **Applications**.

1. Choose **Add** to create a new application.

1. Enter a name for your application.

1. In the form mark the following as required: **Client Authentication** , **PKCE**.

1. For authorized redirect URLs, add the following:

   ```
   https://bedrock-agentcore.region.amazonaws.com/identities/oauth2/callback
   ```

1. Add the necessary scopes for your application.

1. Record the client ID and client secret. You’ll need this information to configure the FusionAuth resource provider in AgentCore Identity.

For more details, refer to [FusionAuth’s OAuth documentation](https://fusionauth.io/docs/lifecycle/authenticate-users/oauth/).

 **Step 2** 

To configure FusionAuth as an outbound resource provider, use the following:

```
{
  "name": "FusionAuth",
  "credentialProviderVendor": "FusionAuthOauth2",
  "oauth2ProviderConfigInput" : {
    "includedOauth2ProviderConfig": {
      "clientId": "your-client-id",
      "clientSecret": "your-client-secret",
      "authorizationEndpoint": "https://your-tenant-authorization-url",
      "tokenEndpoint": "https://your-tenant-token-endpoint",
      "issuer": "https://your-tenant-token-issuer"
    }
  }
}
```

# GitHub
<a name="identity-idp-github"></a>

GitHub can be configured as an AgentCore Identity credential provider for outbound resource access. This allows your agents to authenticate users through GitHub’s OAuth2 service and obtain access tokens for GitHub API resources.

## Outbound
<a name="identity-idp-github-outbound"></a>

 **Step 1** 

Use the following procedure to set up a GitHub OAuth2 application and obtain the necessary client credentials for AgentCore Identity.

 **To configure a GitHub OAuth2 application** 

1. Choose the profile picture of your github account and choose **Settings**.

1. Choose **Developer settings**.

1. Choose **OAuth Apps**.

1. On the OAuth2 apps page choose **New OAuth App**.

1. Enter the necessary details specific to your application. For authorization callback URL enter the following:
   +  `https://bedrock-agentcore.region.amazonaws.com/identities/oauth2/callback` 

1. Choose **Register application** to create your Github OAuth app.

1. On Github’s OAuth Apps page, go to your newly created provider.

1. Under the client secrets section, choose **Generate a new client secret**.

1. Make a note of the newly created client secret. You’ll need this to configure your Github application with AgentCore Identity.
**Note**  
Github only returns the full secret when it is created. If you lose track of it you’ll need to recreate the client secret to configure the provider in AgentCore Identity.

For more details, refer to Github’s documentation [Creating an OAuth app](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/creating-an-oauth-app).

 **Step 2** 

To configure the outbound GitHub resource provider, use the following:

```
{
        "name": "NAME",
        "credentialProviderVendor": "GithubOauth2",
        "oauth2ProviderConfigInput": {
            "GithubOauth2ProviderConfigInput": {
                "clientId": "your-client-id",
                "clientSecret": "your-client-secret",
            }
        },
    }
```

# Google
<a name="identity-idp-google"></a>

Google can be configured as an AgentCore Identity credential provider for outbound resource access. This allows your agents to authenticate users through Google’s OAuth2 service and obtain access tokens for Google API resources.

## Outbound
<a name="identity-idp-google-outbound"></a>

 **Step 1** 

Use the following procedure to set up a Google OAuth2 application and obtain the necessary client credentials for AgentCore Identity.

 **To configure a Google OAuth2 application** 

1. Create a [developer account with Google](https://developers.google.com/identity).

1. Sign in to the [Google Cloud Platform console](https://console.cloud.google.com/home/dashboard).

1. From the top navigation bar, choose **Select a project** . If you already have a project in the Google platform, this menu displays your default project instead.

1. Choose **NEW PROJECT**.

1. Enter a name for your product and then choose **CREATE**.

1. On the left navigation bar, choose **APIs and Services** , and then choose **OAuth consent screen**.

1. Enter the app information, an **App domain** , **Authorized domains** , and **Developer contact information** . Your **Authorized domains** must include `bedrock-agentcore.region.amazonaws.com` . Choose **SAVE AND CONTINUE**.

1. Under **Scopes** , choose **Add or remove scopes** , and then choose the scopes necessary for your application.

1. Expand the left navigation bar again, choose **APIs and Services** , and then choose **Credentials**.

1. Choose **CREATE CREDENTIALS** , and then choose **OAuth client ID**.

1. Choose an **Application type** and give your client a **Name**.

1. Under **Authorized redirect URIs** , choose **ADD URI** . Enter the following:
   +  `https://bedrock-agentcore.region.amazonaws.com/identities/oauth2/callback` 

1. Choose **CREATE**.

1. Securely store the values that Google displays under **Your client ID** and **Your client secret** . Provide these values to AgentCore Identity when you add a Google credential provider.

 **Step 2** 

To configure the outbound Google resource provider, use the following:

```
{
        "name": "NAME",
        "credentialProviderVendor": "GoogleOauth2",
        "oauth2ProviderConfigInput": {
            "GoogleOauth2ProviderConfigInput": {
                "clientId": "your-client-id",
                "clientSecret": "your-client-secret",
            }
        },
    }
```

# HubSpot
<a name="identity-idp-hubspot"></a>

HubSpot can be configured as an AgentCore Identity credential provider for outbound resource access. This allows your agents to authenticate users through HubSpot’s OAuth2 service and obtain access tokens for HubSpot API resources.

**Note**  
HubSpot does not support the M2M/Client Credentials flow.

## Outbound
<a name="identity-idp-hubspot-outbound"></a>

 **Step 1** 

Use the following procedure to set up a HubSpot OAuth2 application and obtain the necessary client credentials for AgentCore Identity.

 **To configure a HubSpot OAuth2 application** 

1. Open the developer console for HubSpot.

1. In the main navigation bar, choose **Apps**.

1. Choose **Create App**.

1. Enter a name for your application.

1. Choose the **Auth** tab and enter the following as a Redirect URL:

   ```
   https://bedrock-agentcore.region.amazonaws.com/identities/oauth2/callback
   ```

1. Configure any scopes that are required for your application.

1. Once your app has been created, go back to the **Auth** tab for your application.

1. Record the client ID and client secret, you’ll need these when creating the HubSpot resource provider in AgentCore Identity.

For more details, refer to [HubSpot’s OAuth quickstart guide](https://developers.hubspot.com/docs/apps/legacy-apps/authentication/oauth-quickstart-guide).

 **Step 2** 

To configure HubSpot as an outbound resource provider, use the following:

```
{
  "name": "Hubspot",
  "credentialProviderVendor": "HubspotOauth2",
  "oauth2ProviderConfigInput" : {
    "includedOauth2ProviderConfig": {
      "clientId": "your-client-id",
      "clientSecret": "your-client-secret"
    }
  }
}
```

**Note**  
When calling GetResourceOAuth2Token, the scopes must include `oauth`.

# LinkedIn
<a name="identity-idp-linkedin"></a>

LinkedIn can be configured as an AgentCore Identity credential provider for outbound resource access. This allows your agents to authenticate users through LinkedIn’s OAuth2 service and obtain access tokens for LinkedIn API resources.

## Outbound
<a name="identity-idp-linkedin-outbound"></a>

 **Step 1** 

Use the following procedure to set up a LinkedIn OAuth2 application and obtain the necessary client credentials for AgentCore Identity.

 **To configure a LinkedIn OAuth2 application** 

1. Open LinkedIn’s developer portal and create an application.

1. In the Auth tab, note the client ID and client secret as you’ll need this information to configure LinkedIn as a provider in AgentCore Identity.

1. Under the OAuth2 settings section, add the following as an authorized redirect URL for the application:

   ```
   https://bedrock-agentcore.region.amazonaws.com/identities/oauth2/callback
   ```

1. Configure any scopes that are necessary for your application.

For more information about LinkedIn authentication, see [Authentication overview](https://learn.microsoft.com/en-us/linkedin/shared/authentication/authentication) on the Microsoft website.

 **Step 2** 

To configure LinkedIn as an outbound resource provider, use the following configuration:

```
{
   "name": "NAME",
   "credentialProviderVendor": "LinkedInOAuth2",
   "oauth2ProviderConfigInput": {
       "linkedInOauth2ProviderConfig": {
           "clientId": "your-client-id",
           "clientSecret": "your-client-secret"
       }
   }
}
```

# Microsoft
<a name="identity-idp-microsoft"></a>

Microsoft Entra ID can be configured as an identity provider for accessing AgentCore Gateway and Runtime, or an AgentCore Identity credential provider for outbound resource access. This allows your agents to authenticate and authorize agent users with Microsoft Entra ID as the identity provider and authorization server, or your agents to obtain credentials to access resources authorized by Microsoft Entra ID.

## Inbound
<a name="identity-idp-microsoft-inbound"></a>

To add Microsoft Entra ID as an identity provider and authorization server for accessing AgentCore Gateway and Runtime, you must:
+ Configure discovery URL for your Microsoft Entra ID Tenant. This helps AgentCore Identity get the metadata related to your OAuth authorization server and token verification keys.
+ Enter valid `aud` claims for the token. This helps validate the tokens coming from your IDP and allows access for tokens that contain the expected claims.

You can configure these as part of configuration of Gateway and Runtime inbound configuration.

Before configuring Microsoft Entra ID as your identity provider, we recommend completing the basic setup steps outlined in [Integrate with Google Drive using OAuth2](identity-getting-started-google.md) . This ensures your development environment and SDK are properly configured before adding identity provider integration.

We support Microsoft Entra ID for v1.0 and v2.0 Access and ID tokens that do not have any custom claims. You can determine which token versions your entra application is issuing by parsing the JWT and looking at the `ver` claim.

For all token types, in your custom authorizer:
+  **Discovery URL** : Discovery URL should be one of the following:
  + For v1.0 tokens use: `https://login.microsoftonline.com/tenantId/.well-known/openid-configuration` 
  + For v2.0 tokens use: `https://login.microsoftonline.com/tenantId/v2.0/.well-known/openid-configuration` 
+  **Allowed audiences** : `aud` should be the Application Id.

### Configurations specific for v1.0 Access Tokens
<a name="identity-idp-microsoft-inbound-v1-access"></a>

When fetching the token from Microsoft Entra:
+ Include in authorization URL a scope like `entra-application-id/.default` alongside any other scopes your application might require. This allows Microsoft to know that you intend to use the access token against resources other than Microsoft’s Graph API and will result in a token that can be validated by AgentCore Identity.

### Configurations Specific for v2.0 AccessTokens
<a name="identity-idp-microsoft-inbound-v2-access"></a>

On Microsoft Entra:
+ While configuring the application, go to the Application Manifest and add `accessTokenAcceptedVersion=2`.
+ On the application, expose an API. The application ID URI and scopes can be whatever is necessary for your application; but, the scope must be included in the authorization URL when retrieving the access token.

### Configurations Specific for v1.0 and v2.0 Id Tokens
<a name="identity-idp-microsoft-inbound-id"></a>

On Microsoft Entra:
+ While configuring the application, Enable ID Token Issuance in Application Registration.
+ Include mandatory `openid` scope while calling the authorize and token endpoint for Microsoft Entra Id during Ingress Flows.

## Outbound
<a name="identity-idp-microsoft-outbound"></a>

To configure the outbound Microsoft resource provider, use the following:

```
{
        "name": "NAME",
        "credentialProviderVendor": "MicrosoftOAuth2",
        "oauth2ProviderConfigInput": {
            "microsoftOauth2ProviderConfig": {
                "clientId": "your-client-id",
                "clientSecret": "your-client-secret",
                "tenantId": "your-microsoft-entra-tenant"
            }
        }
    }
```

# Notion
<a name="identity-idp-notion"></a>

Notion can be configured as an AgentCore Identity credential provider for outbound resource access. This allows your agents to authenticate users through Notion’s OAuth2 service and obtain access tokens for Notion API resources.

## Outbound
<a name="identity-idp-notion-outbound"></a>

 **Step 1** 

Use the following procedure to set up a Notion OAuth2 application and obtain the necessary client credentials for AgentCore Identity.

 **To configure a Notion OAuth2 application** 

1. Open [https://www.notion.so/my-integrations](https://www.notion.so/my-integrations).

1. Choose **\$1 New integration**.

1. Choose **Public integration**.

1. Provide a name for your integration.

1. Choose **Submit**.

1. On the integration details page, open the **OAuth Domain & URIs** section and add the following as a redirect URI:

   ```
   https://bedrock-agentcore.region.amazonaws.com/identities/oauth2/callback
   ```

1. Record the OAuth client ID and OAuth client secret as you’ll need this information to configure the Notion resource provider in AgentCore Identity.

For more details, refer to [Notion’s authorization documentation](https://developers.notion.com/docs/authorization).

 **Step 2** 

To configure Notion as an outbound resource provider, use the following:

```
{
  "name": "Notion",
  "credentialProviderVendor": "NotionOauth2",
  "oauth2ProviderConfigInput" : {
    "includedOauth2ProviderConfig": {
      "clientId": "your-client-id",
      "clientSecret": "your-client-secret"
    }
  }
}
```

# Okta
<a name="identity-idp-okta"></a>

Okta can be configured as an identity provider for accessing AgentCore Gateway and Runtime, or an AgentCore Identity credential provider for outbound resource access. This allows your agents to authenticate and authorize agent users with Okta as the identity provider and authorization server, or your agents to obtain credentials to access resources authorized by Okta.

## Inbound
<a name="identity-idp-okta-inbound"></a>

To add Okta as an identity provider and authorization server for accessing AgentCore Gateway and Runtime, you must:
+ Configure a discovery URL from your Okta tenant. This helps AgentCore Identity get the metadata related to your OAuth authorization server and token verification keys.
+ Enter valid `aud` claims for the token. This helps validate the tokens coming from your IdP and allows access for tokens that contain expected claims.

 **To configure Okta for inbound authentication** 

1. Open the Okta developer console.

1. In the left navigation bar, choose **Applications**.

1. Choose **Create App Integration**.

1. Choose **OIDC - OpenID Connect** as the sign-in method for your application.

1. Choose **Web Application** as your application type.

1. Provide a name for your application.

1. Select **Authorization Code** and/or **Client Credentials** depending on your needs.

1. For **Sign-in redirect URIs** add your application endpoint that will receive the Okta token.

1. Adjust the **Assignments** section as necessary depending on your needs.

1. Choose **Save**.

1. Create an Okta API to represent your application:
   + In the left navigation bar, choose **Security**.
   + Go to **API** and choose **Add Authorization Server**.
   + Follow the flow to create an authorization server dedicated to your Okta tenant.
   + Once the authorization server has been created, choose the **Access Policies** tab on the overview page to configure an appropriate access policy.
   + Define the necessary custom scopes for the authorization server that is needed for your application.

1. Construct the discovery URL for your Okta tenant:

   ```
   https://your-tenant.okta.com/oauth2/your-authorization-server
   ```

1. Configure Inbound Auth with the following values:
   +  **Discovery URL:** The URL constructed in the previous step
   +  **Allowed Audiences:** The audience value you provided when creating the API in step 11

For more details, refer to [Okta’s documentation](https://developer.okta.com/docs/concepts/oauth-openid/).

### Add a client\$1id claim into access token claims
<a name="identity-idp-okta-client-id-claim"></a>

Okta by default does not include `client_id` as a standard claim in their tokens. To populate the claim in the token, you need to customize the claims through the authorization server that you use to issue tokens.

 **To add client\$1id claim to access tokens** 

1. In the left navigation bar, choose **Security** . Go to **API** and choose the authorization server that you intend to use for your application.

1. In the details page for the authorization server, choose the **Claims** tab and choose **Add Claim**.

1. Name the new claim **client\$1id** and set the value to **app.clientId**.

1. Set **Include in token type** to **Access Token**.

1. Choose **Save**.

For more details, refer to [Okta’s documentation](https://developer.okta.com/docs/guides/customize-tokens-returned-from-okta/main/).

## Outbound
<a name="identity-idp-okta-outbound"></a>

Follow the same steps for configuring Okta as an inbound provider; however, when configuring the **Sign-in redirect URIs** add the callback URL that is assigned to your provider when creating the provider in AgentCore Identity.

To configure Okta as an outbound resource provider in AgentCore Identity, use the following:

```
{
  "name": "Okta",
  "credentialProviderVendor": "OktaOauth2",
  "oauth2ProviderConfigInput" : {
    "includedOauth2ProviderConfig": {
      "clientId": "your-client-id",
      "clientSecret": "your-client-secret",
      "authorizationEndpoint": "https://your-tenant.okta.com/oauth2/your-authorization-server/v1/authorize",
      "tokenEndpoint": "https://your-tenant.okta.com/oauth2/your-authorization-server/v1/token",
      "issuer": "https://your-tenant.okta.com/oauth2/your-authorization-server"
    }
  }
}
```

# OneLogin
<a name="identity-idp-onelogin"></a>

OneLogin can be configured as an AgentCore Identity credential provider for outbound resource access. This allows your agents to authenticate users through OneLogin’s OAuth2 service and obtain access tokens for OneLogin API resources.

## Outbound
<a name="identity-idp-onelogin-outbound"></a>

 **Step 1** 

Use the following procedure to set up a OneLogin OAuth2 application and obtain the necessary client credentials for AgentCore Identity.

 **To configure a OneLogin OAuth2 application** 

1. Open the OneLogin Administration panel.

1. Add a new app.

1. Search for OIDC and select the OpenId Connect app.

1. Choose a name for your application and choose **Save**.

1. On the page for the app, go to the **Configuration** tab and add the following as a redirect URI:

   ```
   https://bedrock-agentcore.region.amazonaws.com/identities/oauth2/callback
   ```

1. Open the **SSO** tab and note the client ID and client secret as you’ll need these to configure the OneLogin app in AgentCore Identity.

1. Change the Token endpoint authentication method to **POST**.

1. Choose **Save**.

 **Step 2** 

To configure OneLogin as an outbound resource provider use the following:

```
{
  "name": "OneLogin",
  "credentialProviderVendor": "OneLoginOauth2",
  "oauth2ProviderConfigInput" : {
    "includedOauth2ProviderConfig": {
      "clientId": "your-client-id",
      "clientSecret": "your-client-secret",
      "authorizationEndpoint": "https://your-tenant.onelogin.com/oidc/2/auth",
      "tokenEndpoint": "https://your-tenant.onelogin.com/oidc/2/token",
      "issuer": "https://your-tenant.onelogin.com/oidc/2"
    }
  }
}
```

# Ping Identity
<a name="identity-idp-pingidentity"></a>

Ping Identity’s PingOne platform can be configured as an AgentCore Identity credential provider for outbound resource access. This allows your agents to authenticate users through PingOne’s OAuth2 service and obtain access tokens for PingOne API resources.

## Outbound
<a name="identity-idp-pingidentity-outbound"></a>

**Note**  
You can only configure a PingOne OAuth2 application as either a user federation or M2M OAuth2 client but not both.

 **Step 1** 

Use the following procedure to set up a PingOne OAuth2 application and obtain the necessary client credentials for AgentCore Identity.

 **To configure a PingOne OAuth2 application** 

1. Sign onto the PingOne admin console.

1. In the left navigation bar, under **Applications** , choose **Application**.

1. On the page, choose the **\$1** icon next to **Applications** to create a new application.

1. To configure your application as a M2M OAuth2 client:
   + Select **Client Credentials** for Grant Type.
   + Select **Client Secret Post** for Token Endpoint Authentication Method.
   + Create a custom resource under Applications→Resources in the tabs on the left side of the page, including a scope. Then, add that scope to the application under its personal **Resources** tab. Then, make sure that scope is present in the 'scopes' field of GetResourceOauth2AccessToken.

1. To configure your application as a user federation Oauth2 client:
   + Select **Code** for Response Type.
   + Select **Authorization Code** for Grant Type.
   + Select **Client Secret Basic** for Token Endpoint Authentication Method.

For more details, refer to [Ping Identity’s PingOne API documentation](https://apidocs.pingidentity.com/pingone/getting-started/v1/api).

 **Step 2** 

To configure PingOne as an outbound resource provider use the following:

```
{
  "name": "PingOne",
  "credentialProviderVendor": "PingOneOauth2",
  "oauth2ProviderConfigInput" : {
    "includedOauth2ProviderConfig": {
      "clientId": "your-client-id",
      "clientSecret": "your-client-secret",
      "authorizationEndpoint": "https://auth.pingone.com/your-env-id/as/authorize",
      "tokenEndpoint": "https://auth.pingone.com/your-env-id/as/token",
      "issuer": "https://auth.pingone.com/your-env-id/as"
    }
  }
}
```

# Reddit
<a name="identity-idp-reddit"></a>

Reddit can be configured as an AgentCore Identity credential provider for outbound resource access. This allows your agents to authenticate users through Reddit’s OAuth2 service and obtain access tokens for Reddit API resources.

## Outbound
<a name="identity-idp-reddit-outbound"></a>

 **Step 1** 

Use the following procedure to set up a Reddit OAuth2 application and obtain the necessary client credentials for AgentCore Identity.

 **To configure a Reddit OAuth2 application** 

1. Open Reddit’s developer console: [https://www.reddit.com/prefs/apps](https://www.reddit.com/prefs/apps).

1. Choose on **create an app**.

1. Select **web app** as the application type.

1. Configure the following as the redirect URI for the application:

   ```
   https://bedrock-agentcore.region.amazonaws.com/identities/oauth2/callback
   ```

1. The client ID for the application is below the high-level summary of the application and the client secret is labelled **secret** . Note these values as you’ll need it to configure the Reddit provider in AgentCore Identity.

For more details, refer to [Reddit’s OAuth2 documentation](https://github.com/reddit-archive/reddit/wiki/oauth2).

 **Step 2** 

To configure Reddit as an outbound resource provider, use the following:

```
{
  "name": "Reddit",
  "credentialProviderVendor": "RedditOauth2",
  "oauth2ProviderConfigInput" : {
    "includedOauth2ProviderConfig": {
      "clientId": "your-client-id",
      "clientSecret": "your-client-secret"
    }
  }
}
```

# Salesforce
<a name="identity-idp-salesforce"></a>

Salesforce can be configured as an AgentCore Identity credential provider for outbound resource access. This allows your agents to authenticate users through Salesforce’s OAuth2 service and obtain access tokens for Salesforce API resources.

## Outbound
<a name="identity-idp-salesforce-outbound"></a>

 **Step 1** 

Use the following procedure to set up a Salesforce OAuth2 application and obtain the necessary client credentials for AgentCore Identity.

 **To configure a Salesforce OAuth2 application** 

1. In the developer portal for Salesforce, create a connected app and enter the name and other requested information specific to your application.

1. Enable and configure the OAuth settings for the application, providing the following as the callback URL:
   +  `https://bedrock-agentcore.region.amazonaws.com/identities/oauth2/callback` 

1. Choose the necessary scopes and permissions your application will need.

1. Choose **Require Proof Key for Code Exchange (PKCE) Extension for Supported Authorization Flows**.

1. Choose **Require Secret for the Web Server Flow**.

1. Choose **Enable Authorization Code and Credentials Flow**.

1. If you wish to use Salesforce as a ClientCredentials/M2M provider then choose **Enable Client Credentials Flow** and follow the prompts.

1. Save your application and copy the client ID and client secret that is issued for the application. You will need these to configure Salesforce in AgentCore Identity.

For more details, refer to Salesforce’s documentation [Define an OpenID Connect Provider](https://help.salesforce.com/s/articleView?id=xcloud.service_provider_define_oid.htm).

 **Step 2** 

To configure the outbound Salesforce resource provider, use the following:

```
{
        "name": "NAME",
        "credentialProviderVendor": "SalesforceOauth2",
        "oauth2ProviderConfigInput": {
            "SalesforceOauth2ProviderConfigInput": {
                "clientId": "your-client-id",
                "clientSecret": "your-client-secret",
            }
        },
    }
```

# Slack
<a name="identity-idp-slack"></a>

Slack can be configured as an AgentCore Identity credential provider for outbound resource access. This allows your agents to authenticate users through Slack’s OAuth2 service and obtain access tokens for Slack API resources.

## Outbound
<a name="identity-idp-slack-outbound"></a>

 **Step 1** 

Use the following procedure to set up a Slack OAuth2 application and obtain the necessary client credentials for AgentCore Identity.

 **To configure a Slack OAuth2 application** 

1. Create a Slack application, enter an app name, and choose the development workspace where the app will be built.

1. Choose the **OAuth & Permissions** section and set the following as the redirect URL for the application:
   +  `https://bedrock-agentcore.region.amazonaws.com/identities/oauth2/callback` 

1. Copy the client ID and client secret that Slack issues for your application. You will need them for configuring the provider in AgentCore Identity.

For more details, refer to Slack’s documentation [Sign in with Slack](https://docs.slack.dev/authentication/sign-in-with-slack/).

 **Step 2** 

To configure the outbound Slack resource provider, use the following:

```
{
        "name": "NAME",
        "credentialProviderVendor": "SlackOauth2",
        "oauth2ProviderConfigInput": {
            "slackOauth2ProviderConfig": {
                "clientId": "your-client-id",
                "clientSecret": "your-client-secret"
            }
        }
    }
```

# Spotify
<a name="identity-idp-spotify"></a>

Spotify can be configured as an AgentCore Identity credential provider for outbound resource access. This allows your agents to authenticate users through Spotify’s OAuth2 service and obtain access tokens for Spotify API resources.

## Outbound
<a name="identity-idp-spotify-outbound"></a>

 **Step 1** 

Use the following procedure to set up a Spotify OAuth2 application and obtain the necessary client credentials for AgentCore Identity.

 **To configure a Spotify OAuth2 application** 

1. Open the developer dashboard for Spotify.

1. Choose **Create an App**.

1. Provide a name and description for your application.

1. Use the following as the **Redirect URI** for your application:

   ```
   https://bedrock-agentcore.region.amazonaws.com/identities/oauth2/callback
   ```

1. Select **Web API** for the API/SDKs that you intend to use for Spotify.

1. Choose **Save**.

1. On the application overview page, choose **Settings**.

1. On the **Basic Information** tab, record the client ID and client secret. You’ll need these values for configuring the Spotify resource provider in AgentCore Identity.

 **Step 2** 

To configure Spotify as an outbound resource provider, use the following:

```
{
  "name": "Spotify",
  "credentialProviderVendor": "SpotifyOauth2",
  "oauth2ProviderConfigInput" : {
    "includedOauth2ProviderConfig": {
      "clientId": "your-client-id",
      "clientSecret": "your-client-secret"
    }
  }
}
```

# Twitch
<a name="identity-idp-twitch"></a>

Twitch can be configured as an AgentCore Identity credential provider for outbound resource access. This allows your agents to authenticate users through Twitch’s OAuth2 service and obtain access tokens for Twitch API resources.

## Outbound
<a name="identity-idp-twitch-outbound"></a>

 **Step 1** 

Use the following procedure to set up a Twitch OAuth2 application and obtain the necessary client credentials for AgentCore Identity.

 **To configure a Twitch OAuth2 application** 

1. Sign in to the Twitch developer console.

1. Choose the **Applications** tab and then choose **Register your Application**.

1. Set a name for your application.

1. For the **OAuth Redirect URLs** field, use the following:

   ```
   https://bedrock-agentcore.region.amazonaws.com/identities/oauth2/callback
   ```

1. Select the application category that is appropriate for the application you’re developing (most likely this will be **Chat bot** ).

1. Set **Client Type** as **Confidential**.

1. Choose **Create**.

1. On the application details page, record the client ID and client secret as you’ll need this information for configuring the Twitch resource provider in AgentCore Identity.

For more details, refer to [Twitch’s app registration documentation](https://dev.twitch.tv/docs/authentication/register-app/).

 **Step 2** 

To configure Twitch as an outbound resource provider, use the following:

```
{
  "name": "Twitch",
  "credentialProviderVendor": "TwitchOauth2",
  "oauth2ProviderConfigInput" : {
    "includedOauth2ProviderConfig": {
      "clientId": "your-client-id",
      "clientSecret": "your-client-secret"
    }
  }
}
```

# X
<a name="identity-idp-x"></a>

X can be configured as an AgentCore Identity credential provider for outbound resource access. This allows your agents to authenticate users through X’s OAuth2 service and obtain access tokens for X API resources.

## Outbound
<a name="identity-idp-x-outbound"></a>

 **Step 1** 

Use the following procedure to set up a X OAuth2 application and obtain the necessary client credentials for AgentCore Identity.

 **To configure an X OAuth2 application** 

1. Open the X developer portal.

1. In the left navigation bar, choose **Project & Apps**.

1. Choose on the X project you’ve created for the application.

1. Under the **Apps** header choose **Add an App**.

1. Choose **Create new**.

1. Provide a name and description for your application.

1. In the left navigation bar, choose the application that was just generated.

1. On the app details page for your new app, choose **Edit** in the User Authentication settings.

1. Select the **App permissions** necessary for your application.

1. For **Type of App** select **Web App, Automated App or Bot**.

1. Under **App Info** enter the following as the callback URL:

   ```
   https://bedrock-agentcore.region.amazonaws.com/identities/oauth2/callback
   ```

1. For **Website URL** enter the URL for your application.

1. Choose **Save**.

1. Under the **Keys and token** tab for your application, go to the **OAuth 2.0 Client ID and Client Secret**.

1. Choose **Generate** and note the client ID and secret that get generated as you’ll need this information to configure the X resource provider in AgentCore Identity.

**Note**  
X only displays the full client secret when it is generated, if you lose this information you’ll need to re-generate the client secret in the X developer portal.

For more details, refer to [X’s OAuth 2.0 documentation](https://docs.x.com/fundamentals/authentication/oauth-2-0/overview).

 **Step 2** 

To configure X as an outbound resource provider, use the following:

```
{
  "name": "X",
  "credentialProviderVendor": "XOauth2",
  "oauth2ProviderConfigInput" : {
    "includedOauth2ProviderConfig": {
      "clientId": "your-client-id",
      "clientSecret": "your-client-secret"
    }
  }
}
```

# Yandex
<a name="identity-idp-yandex"></a>

Yandex can be configured as an AgentCore Identity credential provider for outbound resource access. This allows your agents to authenticate users through Yandex’s OAuth2 service and obtain access tokens for Yandex API resources.

## Outbound
<a name="identity-idp-yandex-outbound"></a>

 **Step 1** 

Use the following procedure to set up a Yandex OAuth2 application and obtain the necessary client credentials for AgentCore Identity.

 **To configure a Yandex OAuth2 application** 

1. Open the developer console for Yandex at [https://oauth.yandex.com/](https://oauth.yandex.com/).

1. Choose **Create app**.

1. Provide a name for your application.

1. For platforms, select **Web services**.

1. Choose **Save and Continue**.

1. Select the permissions necessary for your application and then choose **Save and Continue**.

1. Configure the following as the redirect URI for the application:

   ```
   https://bedrock-agentcore.region.amazonaws.com/identities/oauth2/callback
   ```

1. Choose **Save and Continue**.

1. Once the client has been created, note the client ID and client secret assigned to your application as you’ll need them for configuring the Yandex provider in AgentCore Identity.

For more details, refer to [Yandex’s OAuth documentation](https://yandex.com/dev/id/doc/en/).

 **Step 2** 

To configure Yandex as an outbound resource provider, use the following:

```
{
  "name": "Yandex",
  "credentialProviderVendor": "YandexOauth2",
  "oauth2ProviderConfigInput" : {
    "includedOauth2ProviderConfig": {
      "clientId": "your-client-id",
      "clientSecret": "your-client-secret"
    }
  }
}
```

# Zoom
<a name="identity-idp-zoom"></a>

Zoom can be configured as an AgentCore Identity credential provider for outbound resource access. This allows your agents to authenticate users through Zoom’s OAuth2 service and obtain access tokens for Zoom API resources.

## Outbound
<a name="identity-idp-zoom-outbound"></a>

**Note**  
You can only configure a Zoom OAuth2 application as either a user federation or M2M OAuth2 client but not both.

 **Step 1** 

Use the following procedure to set up a Zoom OAuth2 application and obtain the necessary client credentials for AgentCore Identity.

 **To configure a Zoom OAuth2 application** 

1. Sign in to the Zoom App Marketplace.

1. Choose **Develop** > **Build App**.

1. For a user federation app, select **General app** and choose **Create**.
   + On the app details page, add a name for your application and select how your application will be managed.
   + In the **OAuth Information** section, for both the OAuth Redirect URL and OAuth Allow Lists sections, use the following as the redirect URL for the application:

     ```
     https://bedrock-agentcore.region.amazonaws.com/identities/oauth2/callback
     ```

1. For a M2M app, select **Server to Server OAuth App** and choose **Create**.
   + Add a name for your application.
   + On the app details page, choose **Scopes** and add the necessary scopes for your application.
   + Open **Information** and provide a company name, and developer contact information.

1. Record the client ID and client secret that have been generated for your application. You’ll need these values to configure the Zoom credential provider in AgentCore Identity.

For more details, refer to [Zoom’s integration documentation](https://developers.zoom.us/docs/integrations/create/).

 **Step 2** 

To configure Zoom as an outbound resource provider, use the following:

```
{
  "name": "Zoom",
  "credentialProviderVendor": "ZoomOauth2",
  "oauth2ProviderConfigInput" : {
    "includedOauth2ProviderConfig": {
      "clientId": "your-client-id",
      "clientSecret": "your-client-secret"
    }
  }
}
```

# Data protection in Amazon Bedrock AgentCore Identity
<a name="identity-data-protection"></a>

The AWS [shared responsibility model](https://aws.amazon.com/compliance/shared-responsibility-model/) applies to data protection in Amazon Bedrock AgentCore Identity. As described in this model, AWS is responsible for protecting the global infrastructure that runs all of the AWS Cloud. You are responsible for maintaining control over your content that is hosted on this infrastructure. This content includes the security configuration and management tasks for the AWS services that you use. For more information about data privacy, see the [Data Privacy FAQ](https://aws.amazon.com/compliance/data-privacy-faq).

For data protection purposes, we recommend that you protect AWS account credentials and set up individual user accounts with IAM. That way each user is given only the permissions necessary to fulfill their job duties. We also recommend that you secure your data in the following ways:
+ Use multi-factor authentication (MFA) with each account.
+ Use SSL/TLS to communicate with AWS resources.
+ Set up API and user activity logging with AWS CloudTrail.
+ Use AWS encryption solutions, along with all default security controls within AWS services.
+ Use advanced managed security services such as Amazon Macie, which assists in discovering and securing personal data that is stored in Amazon S3.

We strongly recommend that you never put sensitive identifying information, such as your customers' account numbers, into free-form fields such as a **Name** field. This includes when you work with Amazon Bedrock AgentCore Identity or other AWS services using the console, API, AWS CLI, or AWS SDKs. Any data that you enter into Amazon Bedrock AgentCore Identity or other services might get picked up for inclusion in diagnostic logs. When you provide a URL to an external server, don’t include credentials information in the URL to validate your request to that server.

**Topics**
+ [

# Data encryption
](identity-data-encryption.md)
+ [

# Set customer managed key policy
](kms-key-policy-configuration.md)
+ [

# Configure with API operations or an AWS SDK
](api-configuration-encryption.md)
+ [

# Configure KMS key for Token Vault on Console
](console-configuration-encryption.md)

# Data encryption
<a name="identity-data-encryption"></a>

Data encryption typically falls into two categories: encryption at rest and encryption in transit.

## Encryption at rest
<a name="encryption-at-rest"></a>

Data within Amazon Bedrock AgentCore Identity is encrypted at rest in accordance with industry standards.

By default, Amazon Bedrock AgentCore Identity encrypts customer data in token vaults with AWS owned keys. You can also configure your token vaults to instead encrypt your information with customer managed keys.

 ** AWS owned key**   
Amazon Bedrock AgentCore Identity encrypts the data in your token vault with an AWS owned KMS key. Keys of this type aren’t visible in AWS KMS.

 **Customer managed key**   
Amazon Bedrock AgentCore Identity encrypts the data in your token vault with a customer managed key. You own the administration of customer managed key policies, rotation, and scheduled deletion.

### Things to know about token vault encryption with customer managed keys
<a name="token-vault-encryption-considerations"></a>
+ Data in your token vault (access tokens) are encrypted at rest with the customer managed key you configure. The token vault ARN is captured in the EncryptionContext.
+ All customer data in your token vault is encrypted at rest, even if you take no action to configure encryption settings.
+ You can’t configure token vault encryption at rest with [multi-Region keys](https://docs.aws.amazon.com/kms/latest/developerguide/multi-region-keys-overview.html) or [asymmetric keys](https://docs.aws.amazon.com/kms/latest/developerguide/symmetric-asymmetric.html) . Amazon Bedrock AgentCore Identity supports only single-region symmetric KMS keys for token vault encryption at rest.
+ You can configure token vault encryption only with a KMS key ARN, not an alias.
+ You can configure CMK for credential provider secrets using AWS Secrets Manager. [Learn more](https://docs.aws.amazon.com/secretsmanager/latest/userguide/manage_update-encryption-key.html).

The following procedures configure encryption at rest in your token vault. For more information about KMS key policies that delegate access to AWS services like Amazon Cognito, see [Permissions for AWS services in key policies](https://docs.aws.amazon.com/kms/latest/developerguide/key-policy-services.html).

# Set customer managed key policy
<a name="kms-key-policy-configuration"></a>

**Note**  
Currently we don’t support configuring CMK on token vault through console.

To use a customer managed key, your key must trust an Amazon Bedrock AgentCore Identity service principal to perform encryption and decryption operations on the key. Configure the [key policy](https://docs.aws.amazon.com/kms/latest/developerguide/key-policies.html) of your KMS key as shown in the following example. The IAM principal that writes this policy must have write access to your KMS key, with `kms:PutKeyPolicy` permission.

# Configure with API operations or an AWS SDK
<a name="api-configuration-encryption"></a>

Set your key configuration in a `SetTokenVaultCMK` API request. The following partial example request body sets the token vault to use the provided customer managed key.

```
"KmsConfiguration": {
    "KeyType": "CUSTOMER_MANAGED_KEY",
    "KmsKeyArn": "arn:aws:kms:us-east-1:111122223333:key/a1b2c3d4-5678-90ab-cdef-EXAMPLE22222"
}
```

The following partial example request body sets a token vault to use an AWS owned key.

```
"KmsConfiguration": {
    "KeyType": "AWS_OWNED_KEY"
}
```

If your `GetTokenVault` response doesn’t include a `KmsConfiguration` parameter, your token vault is configured to encrypt data at rest with an AWS owned key.

# Configure KMS key for Token Vault on Console
<a name="console-configuration-encryption"></a>

The KMS key configuration determines how your token vault encrypts data at rest. You can choose between an AWS owned key or a customer managed key (stored in your account and managed through AWS KMS).

## To configure AWS KMS encryption for your token vault
<a name="configure-kms-encryption-steps"></a>
+ Open the [AgentCore Identity](https://console.aws.amazon.com/bedrock-agentcore/identity) console.
+ In the **KMS key (Token vault)** section, choose **Edit**.
+ In the KMS key selection section, your token vault is encrypted by default with a key that AWS owns and manages for you at a token vault level. To choose a different key, customize your encryption settings:
  +  ** AWS owned key (default)** : Leave the checkbox unselected. The KMS key is owned and managed by AWS.
  +  **Customer managed key** : Select the checkbox and provide the KMS key ARN. The key is stored in your account and is managed by AWS Key Management Service (AWS KMS).
+ Choose **Save changes** to update the KMS key configuration for your token vault.
+ To confirm the encryption type, check the **KMS key (Token vault)** details in the AgentCore Identity console.

# Tagging AgentCore Identity resources
<a name="identity-tagging"></a>

Amazon Bedrock AgentCore Identity supports comprehensive tagging capabilities across its resource hierarchy to enable better resource management, cost allocation, access control, and operational visibility. For general information about tags, including syntax and usage, see [Tagging AgentCore resources](tagging.md).

## Benefits of tagging AgentCore Identity resources
<a name="identity-tagging-benefits"></a>

Tags help you accomplish the following key objectives with your AgentCore Identity resources:

### Identify and organize AWS resources
<a name="identity-tagging-organize"></a>

Many AWS services support tagging, allowing you to assign the same tag to resources from different services. This helps indicate which resources are related. You could assign the same tag to a workload identity that you assign to an DynamoDB table or Lambda function that uses those credentials.

 **Example scenario** : Tag all resources for a customer service application with `Application=customer-service-bot` to easily identify and manage related resources across different AWS services, as shown in the following sample code.

```
{
  "name": "customer-service-workload-identity",
  "tags": {
    "Application": "customer-service-bot",
    "Component": "authentication",
    "Owner": "customer-experience-team"
  }
}
```

### Track AWS costs
<a name="identity-tagging-costs"></a>

You can activate cost allocation tags on the AWS Billing and Cost Management dashboard. AWS uses these tags to categorize your costs and deliver a monthly cost allocation report. This enables you to:
+ Allocate identity service costs to specific projects or teams
+ Track spending patterns across different environments
+ Optimize costs based on usage analysis

 **Example scenario** : Use `CostCenter=ai-platform` and `Project=bedrock-agents` tags to track how much your AI platform team spends on identity services for the Bedrock agents project, as shown in the following sample code.

```
{
  "name": "customer-service-workload-identity",
  "tags": {
    "CostCenter": "ai-platform",
    "Project": "bedrock-agents",
    "Environment": "production",
    "Team": "customer-experience"
  }
}
```

### Control access based on tags
<a name="identity-tagging-access-control"></a>

You can control access by specifying tag keys and values in the conditions for IAM policies. This enables attribute-based access control (ABAC) where permissions are granted based on resource tags.

 **Example scenario** : Allow a user to access workload identities only if they have an `Owner` tag with a value matching the user’s team name, or restrict access to production credential providers based on `Environment=production` tags, as shown in the following sample code.

```
{
"Version": "2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "bedrock-agentcore:GetWorkloadIdentity",
        "bedrock-agentcore:UpdateWorkloadIdentity"
      ],
      "Resource": "*",
      "Condition": {
        "StringEquals": {
          "bedrock-agentcore:ResourceTag/Owner": "${aws:PrincipalTag/Team}"
        }
      }
    }
  ]
}
```

## Resource architecture
<a name="identity-resource-architecture"></a>

Amazon Bedrock AgentCore Identity manages five distinct resource types organized in a hierarchical structure:

### Primary resources
<a name="identity-primary-resources"></a>

The following are the primary resources in the AgentCore Identity service hierarchy:
+  **Workload Identity Directory** : `arn:aws:bedrock-agentcore:${Region}:${Account}:workload-identity-directory/default` 
+  **Token Vault** : `arn:aws:bedrock-agentcore:${Region}:${Account}:token-vault/default` 

### Sub-resources
<a name="identity-sub-resources"></a>

The following are the sub-resources that exist within the primary resource hierarchy:
+  **Workload Identity** : `arn:aws:bedrock-agentcore:${Region}:${Account}:workload-identity-directory/default/workload-identity/${workload identity name}` 
+  **OAuth2 Credential Provider** : `arn:aws:bedrock-agentcore:${Region}:${Account}:token-vault/default/oauth2credentialprovider/${oauth2CredentialProviderName}` 
+  **API Key Credential Provider** : `arn:${Partition}:bedrock-agentcore:${Region}:${Account}:token-vault/default/apikeycredentialprovider/${APIkeyCredentialproviderName}` 

## Tagging support matrix
<a name="identity-tagging-support"></a>

The following table shows the tagging capabilities for each AgentCore Identity resource type:


| Resource Type | Tag on Create | Basic Tagging | TBAC Support | 
| --- | --- | --- | --- | 
|  Workload Identity  |  ✅  |  ✅  |  ✅  | 
|  OAuth2 Credential Provider  |  ✅  |  ✅  |  ✅  | 
|  API Key Credential Provider  |  ✅  |  ✅  |  ✅  | 
|  Workload Identity Directory  |  ❌  |  ✅  |  ✅  | 
|  Token Vault  |  ❌  |  ✅  |  ✅  | 

**Note**  
TBAC (Tag-Based Access Control) support means you can use resource tags in IAM policy conditions to control access to these resources.