Hi Shin Kim,
Thanks for the detailed context! Since you're working with Azure AI Foundry AI Agents and trying to get a tool to authenticate via Bearer Token using a custom key connection, and it’s returning a 401 Unauthorized, here's a breakdown of why this might be happening and how to fix it:
I understand that:
· You're using the Custom Key Connection.
· It successfully triggers the API call, but does not attach the Bearer token properly.
· The target API returns 401, suggesting invalid/missing Authorization headers.
Root Cause:
In Azure AI Foundry, Custom Key Connections are primarily designed for static key-value pairs, and Bearer token handling might require a slightly different setup — especially for the Authorization header, which must follow this exact format:
Authorization: Bearer <your_token>
If the connection is defined like:
{
"Authorization": "Bearer <your_token>"
}
and the tool isn’t injecting it properly, the issue could be:
· The connection is not being referenced correctly in the tool.
· The tool is not mapping the connection key into the Authorization header explicitly.
· AI Agent doesn't default to using the connection key in the right header format.
Recommended Fixes:
1.Use Authorization header manually in the Tool definition
If you're using a tool defined in the YAML or UI, modify the tool definition like so:
- name: CallMyAPI
description: Call external API with bearer token
url: https://api.example.com/endpoint
method: GET
headers:
Authorization: "Bearer {{connections.my_bearer_connection.token}}"
connection: my_bearer_connection
Ensure:
· The connection name exactly matches the Custom Key Connection name.
· Inside the connection, the key is set like:
{
"token": "<actual_bearer_token>"
}
2.Define Authorization header directly in the connection (Advanced)
If Foundry supports it (depending on version), define your connection as:
{
"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR..."
}
Then in the tool definition, use:
headers:
Authorization: "{{connections.my_bearer_connection.Authorization}}"
This bypasses the need for manually concatenating "Bearer".
3.Use Python SDK (if possible) to confirm
If you’re programmatically testing it using the SDK before integrating in the agent, simulate the request like:
import requests
url = "https://api.example.com/endpoint"
headers = {
"Authorization": "Bearer YOUR_TOKEN_HERE"
}
response = requests.get(url, headers=headers)
print(response.status_code, response.text)
If this works but the agent doesn’t, it confirms the token itself is fine but the agent setup is wrong.
Hope this helps. If you have any follow-up questions, please let me know. I would be happy to help.
**
Please do not forget to "Accept the answer” and “up-vote” wherever the information provided helps you, this can be beneficial to other community members.
Thank you!