[Python] Get User access token from within ActivityHandler - Botframework Python SDK

Discussão em 'Python' iniciado por Stack, Dezembro 7, 2024.

  1. Stack

    Stack Membro Participativo

    A Teams Bot application has been developed using the Bot Framework Python SDK (v4.14.4), where BotFrameworkAdapter and an extended ActivityHandler class have been properly initialized. The bot is functioning correctly, allowing chat interactions and responses.

    The goal is to retrieve the user access token from the incoming request (the token included in the header when a user sends a message) to make an external API call. However, only the TurnContext object is available in the on_turn or on_message_activity methods of the ActivityHandler.

    In the app.py file, the routing method for /api/messages is as follows:

    # bot_framework_adapter and activity_handler are initialized at the global level

    async def messages(req: Request) -> Response:
    # .. some other logic
    auth_token = req.headers.get("Authorization", "")
    response = await bot_framework_adapter.process_activity(activity, auth_token, activity_handler.on_turn)


    Reference: https://github.com/microsoft/BotBuilder-Samples/tree/main/archive/samples/python/11.qnamaker

    My application almost implements the above sample reference, except for the on_message_activity on the BOT/ActivityHandler.

    Currently, I have overriden process_activity and process_activity_with_identity on the BotFrameworkAdapter class in my extended class and added a new key-value pair for this auth_token on context.turn_state dictionary.

    But is it possible to access/reconstruct this auth_token within the ActivityHandler methods (maybe using the TurnContext object), or is there a recommended workaround for making an external API call with the same user authorization used for the Bot?

    Note: I am consuming this Bot through Microsoft Teams application using the Azure Bot service. So, the auth_token I am referring earlier is the token being sent from the teams application.

    Note: The botframework SDK is being retired, but I have some bots already developed and in production. As of now I am looking for a quick solution/workaround if it is possible.

    Thanks in advance.

    Continue reading...

Compartilhe esta Página