Search code examples
node.jsbotframeworkmicrosoft-teams

How to fetch user access token after authentication in Microsoft Teams Bot?


I am developing my first bot from Microsoft Teams.

I want the user to input commands in the bot, the bot should send requests to my external web sever and display the results as adaptive cards. I was able to authenticate the bot with my external server. The bot shows the user access token after authentication. Perfect!

How can I get the user's access token in my bot code or web server to process the incoming request from the bot. Here's what my bot code looks like.

this.onMessage(async (context, next) => {

     //I need a way to get the user's access token here 
     //or a way to fetch the access token from my web server 
     //based on some id in the context.
     const response = await myWebService.getData(context);

     // Run the Dialog with the new message Activity.
     await this.dialog.run(context, this.dialogState);
     await next();
});

What am I missing here?


Solution

  • You can capture the token during the login process. Assuming you have structured your login process something like the below, the result of the user logging in is passed from the promptStep() to the loginStep(). It is available in stepContext.result which I have assigned to tokenResponse and return to the user as text in an activity.

    It is here that you can perform the additional logic you need to.

    async promptStep(stepContext) {
        return await stepContext.beginDialog(OAUTH_AAD_PROMPT);
    }
    
    async loginStep(stepContext) {
        // Get the token from the previous step. Note that we could also have gotten the
        // token directly from the prompt itself. There is an example of this in the next method.
        const tokenResponse = stepContext.result;
        if (tokenResponse) {
            return await stepContext.context.sendActivity(`Your token is: ${ tokenResponse.token }`);
        }
        await stepContext.context.sendActivity('Login was not successful, please try again.');
        return await stepContext.next();
    }
    

    Hope of help!