AI Agent deployed on App Service returns “Operation returned an invalid status code 'Unauthorized'” when replying through Azure Bot Service

Lightning Minds 0 Reputation points
2025-10-22T07:29:22.6233333+00:00

I’m hosting a FastAPI-based AI Agent backend on Azure App Service (Python) and connected it to Azure Bot Service. The bot receives messages successfully from Web Chat and the Bot Framework service, but every time it tries to send a reply, I get this error:

botbuilder.schema._models_py3.ErrorResponseException: Operation returned an invalid status code 'Unauthorized'

This happens inside:

await turn_context.send_activity(agent_reply)

This only affects outbound messages (inbound works fine).

I’ve already verified the following:

  • The app is registered in Microsoft Entra ID and the same MicrosoftAppId is configured in both the Bot Channel Registration and the App Service.
  • MicrosoftAppPassword uses the correct Secret Value.

The app is set to multi-tenant: “Accounts in any organizational directory and personal Microsoft accounts.”

API permissions include openid, User.Read, and profile (Delegated) with admin consent granted.

  • Region trust has been added in code:
      MicrosoftAppCredentials.trust_service_url("https://smba.trafficmanager.net/amer/")
    
    The App Service is deployed in Central US, and the Bot Service is Global.
  • Token test for https://api.botframework.com/.default returns 200 OK and valid tokens.

Despite this, outbound messages fail with Unauthorized.

When the app was single-tenant, I got:

AADSTS700016: Application with identifier '...' was not found in the directory 'Bot Framework'

After switching to multi-tenant, I get:

Operation returned an invalid status code 'Unauthorized'

So token acquisition now succeeds, but the outbound call from the Bot Adapter still fails authentication.

Any help would be much appreciated. Thanks.

Azure AI Bot Service
Azure AI Bot Service
An Azure service that provides an integrated environment for bot development.
{count} votes

1 answer

Sort by: Most helpful
  1. Sina Salam 25,761 Reputation points Volunteer Moderator
    2025-10-22T10:15:12.0266667+00:00

    Hello Lightning Minds,

    Welcome to the Microsoft Q&A and thank you for posting your questions here.

    I understand that your AI Agent deployed on App Service returns “Operation returned an invalid status code 'Unauthorized'” when replying through Azure Bot Service.

    To fix this, ensure your MicrosoftAppId and MicrosoftAppPassword in App Service exactly match those in your Bot Channel Registration and App Registration. Your adapter should use the correct credentials as shown below:

    from botbuilder.core import BotFrameworkAdapterSettings, BotFrameworkAdapter
    import os
    settings = BotFrameworkAdapterSettings(os.getenv("MicrosoftAppId"), os.getenv("MicrosoftAppPassword"))
    adapter = BotFrameworkAdapter(settings)
    

    Before sending any message, dynamically trust the serviceUrl received from the incoming activity instead of hardcoding a region, as shown:

    from botframework.connector.auth import MicrosoftAppCredentials
    MicrosoftAppCredentials.trust_service_url(turn_context.activity.service_url)
    

    Next, verify that your bot obtains a valid token for the correct audience by running:

    from botframework.connector.auth import MicrosoftAppCredentials
    import asyncio, os
    async def test_token():
        creds = MicrosoftAppCredentials(os.getenv("MicrosoftAppId"), os.getenv("MicrosoftAppPassword"))
        print(await creds.get_access_token())
    asyncio.run(test_token())
    

    When decoded, the JWT’s aud claim must be https://api.botframework.com/. If not, manually request the token using:

    curl -X POST -d "grant_type=client_credentials&client_id=<APPID>&client_secret=<SECRET>&scope=https://api.botframework.com/.default" https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token
    

    to validate the correct scope and endpoint.

    Additionally, confirm that Managed Identity is not conflicting with App ID based authentication, and that your Bot Channel Registration and App Service regions align (for example, both in Central US or Global). Use the latest botbuilder-core SDK (v4.15+) to avoid known token audience bugs. For multi-tenant configurations, grant admin consent to https://api.botframework.com/.default and ensure all external tenants where the bot operates have approved the app.

    If issues persist, enable debug logs for the connector to capture the outbound HTTP response body for sub-error details. You can review official Microsoft documentation on Bot Framework authentication and token acquisition: - https://free.blessedness.top/en-us/azure/bot-service/rest-api/bot-framework-rest-connector-authentication and https://free.blessedness.top/en-us/azure/bot-service/bot-service-troubleshoot-authentication-problems for more details.

    I hope this is helpful! Do not hesitate to let me know if you have any other questions or clarifications.


    Please don't forget to close up the thread here by upvoting and accept it as an answer if it is helpful.


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.