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.