Add authentication to your Teams bot

You can create bots in Microsoft Teams that access resources on behalf of the user, such as a mail service. You can use Azure Bot Service v4 SDK authentication, based on OAuth 2.0. This method makes it easier to develop a bot that can use authentication tokens based on the user's credentials. The key is the use of identity providers.

OAuth 2.0 is an open standard for authentication and authorization used by Microsoft Entra ID and many other identity providers. A basic understanding of OAuth 2.0 is a prerequisite for working with authentication in Teams.

See OAuth 2 Simplified for a basic understanding, and OAuth 2.0 for the complete specification.

For more information about how the Azure Bot Service handles authentication, see User authentication within a conversation.

In this article you'll learn:

  • How to create an authentication-enabled bot. Use cs-auth-sample to handle user sign-in credentials and the generating the authentication token.
  • How to deploy the bot to Azure and associate it with an identity provider. The provider issues a token based on user sign-in credentials. The bot can use the token to access resources, such as a mail service, which require authentication. For more information, see Microsoft Teams authentication flow for bots.
  • How to integrate the bot within Microsoft Teams. Once the bot is integrated, you can sign in and exchange messages with it in a chat.

Prerequisites

Create the resource group

The resource group and the service plan aren't strictly necessary, but they allow you to conveniently release the resources you create. We recommend that you keep your resources organized and manageable.

You use a resource group to create individual resources for the Bot Framework. For performance, ensure that these resources are located in the same Azure region.

  1. In your browser, sign into the Microsoft Azure portal.
  2. In the left navigation panel, select Resource groups.
  3. In the upper left of the displayed window, select Add tab to create a new resource group. Provide the following details:
    1. Subscription. Use your existing subscription.
    2. Resource group. Enter the name for the resource group. An example could be TeamsResourceGroup. Remember that the name must be unique.
    3. From the Region dropdown menu, select West US, or a region close to your applications.
    4. Select the Review and create button. You should see a banner that reads Validation passed.
    5. Select the Create button. It might take a few minutes to create the resource group.

Tip

As with the resources you'll create later in this tutorial, it's a good idea to pin this resource group to your dashboard for easy access. If you'd like to do so, select the pin icon πŸ“Œ in the upper right of the dashboard.

Create the service plan

  1. In the Azure portal, on the left navigation panel, select Create a resource.
  2. In the search box, type App Service Plan. Select the App Service Plan card from the search results.
  3. Select Create.
  4. Provide the following information:
    1. Subscription. You can use an existing subscription.
    2. Resource Group. Select the group you created earlier.
    3. Name. Enter the name for the service plan. An example could be TeamsServicePlan. Remember that the name must be unique, within the group.
    4. Operating System. Select Windows or your applicable OS.
    5. Region. Select West US or a region close to your applications.
    6. Pricing Tier. Select Standard S1, which is the default value.
    7. Select the Review and create button. You should see a banner that reads Validation passed.
    8. Select Create. It might take a few minutes to create the app service plan. The plan is listed in the resource group.

Create Azure Bot resource registration

The Azure Bot resource registration registers your web service as a bot with the Bot Framework, which provides you with a Microsoft App ID and App password (client secret).

Important

You only need to register your bot if it's not hosted in Azure. If you created a bot through the Azure portal then it's already registered with the service. If you created your bot through the Bot Framework or Developer Portal your bot isn't registered in Azure.

  1. Visit Azure portal and search for Azure Bot in Create a resource section.

  2. Open the Azure Bot and select Create.

  3. Enter bot handle name in Bot handle field.

  4. Select your Subscription from the dropdown list.

  5. Select your Resource group from the dropdown list.

  6. Select Type of App as Multi Tenant for Microsoft App ID.

    Screenshot shows how to select multitenant for Microsoft AppID.

  7. Select Review + create.

    Screenshot shows how to create Azure bot.

  8. If the validation passes, select Create.

    Azure provisions your bot in a few moments.

    Screenshot shows how Azure bot validation passes.

  9. Select Go to resource. The bot and the related resources are listed in the resource group.

    Screenshot shows how to select resources group.

    Your Azure bot is created.

    Screenshot shows how to create Azure bot resources.

To create client secret:

  1. In Settings, select Configuration. Save the Microsoft App ID (client ID) for future reference.

    Screenshot shows how to add Microsoft App ID to create client secret.

  2. Next to Microsoft App ID, select Manage.

    Screenshot shows how to create and manage a bot.

  3. In the Client secrets section, select New client secret.Add a client secret window appears.

    Screenshot shows how to create new client secret.

  4. Enter Description and select Add.

    The screenshot shows how to enter description for the client secret.

  5. In the Value column, select Copy to clipboard and save the client secret ID for future reference.

    The screenshot shows how to save the client secret ID for future reference.

To add the Microsoft Teams channel:

  1. Go to Home.

    Screenshot shows you the bot home page.

  2. Open your bot from the Recent resources section.

  3. Select Channels in the left pane and select Microsoft Teams .

    Screenshot shows how to select Teams in channels.

  4. Select the checkbox to accept the terms of service and select Agree.

    Screenshot shows how to set the terms if service.

  5. Select Save.

    Screenshot shows how to add Microsoft Teams channel.

For more information, see Create a bot for Teams.

Create the identity provider

You need an identity provider for authentication. In this procedure, you use a Microsoft Entra provider. Alternatively, you can also use other Microsoft Entra ID supported identity providers.

  1. In the Azure portal, on the left navigation panel, select Microsoft Entra ID.

    Tip

    You must create and register this Microsoft Entra resource in a tenant in which you can consent to delegate permissions requested by an application. For instructions on creating a tenant, see Access the portal and create a tenant.

  2. In the left panel, select App registrations.

  3. In the right panel, select the New registration tab, in the upper left.

  4. Provide the following information:

    1. Name. Enter the name for the application. An example could be BotTeamsIdentity. Remember that the name must be unique.
    2. Select the Supported account types for your application. Select Accounts in any organizational directory (Any Microsoft Entra ID tenant - Multitenant) and personal Microsoft accounts (e.g. Skype, Xbox).
    3. For the Redirect URI:
      βœ“Select Web.
      βœ“ Set the URL to https://token.botframework.com/.auth/web/redirect.
    4. Select Register.
  5. After Azure creates the app, it displays the Overview page for the app. Copy and save the following information to a file:

    1. The Application (client) ID value. Use this value later as the Client ID when you register this Azure identity application with your bot.
    2. The Directory (tenant) ID value. Use this value later as the Tenant ID when you register this Azure identity application with your bot.
  6. In the left panel, select Certificates & secrets to create a client secret for your application.

    1. Under Client secrets, select βž• New client secret.
    2. Add a description to identify this secret from others you might need to create for this app, such as Bot identity app in Teams.
    3. Set Expires to your selection.
    4. Select Add.
    5. Before leaving this page, record the secret. Use this value later as the Client secret when you register your Microsoft Entra application with your bot.

Configure the identity provider connection and register it with the bot

Note

There are two options for Service Providers here, Azure Active Directory v1 and Azure Active Directory v2. The differences between the two providers are summarized here, but in general, v2 provides more flexibility with respect to changing bot permissions. Graph API permissions are listed in the scopes field, and as new ones are added, bots will allow users to consent to the new permissions on the next sign in. For v1, the bot consent must be deleted by the user for new permissions to be prompted in the OAuth dialog.

Microsoft Azure Active Directory (Azure AD) v1

  1. In the Azure portal, select your resource group from the dashboard.

  2. Select your bot registration link.

  3. Open the resource page and select Configuration under Settings.

  4. Select Add OAuth Connection Settings. The following image displays the corresponding selection in the resource page:

    SampleAppDemoBot configuration

  5. Complete the form as follows:

    1. Name. Enter a name for the connection. You use this name in your bot in the appsettings.json file. For example, BotTeamsAuthADv1.

    2. Service Provider. Select Azure Active Directory. Once you select this option, the Azure Active Directory-specific fields are displayed.

    3. Client id. Enter the Application (client) ID that you recorded for your Azure identity provider app.

    4. Client secret. Enter the secret that you recorded for your Azure identity provider app.

    5. Grant Type. Enter authorization_code.

    6. Login URL. Enter https://login.microsoftonline.com.

    7. Tenant ID, enter the Directory (tenant) ID that you recorded earlier for your Azure identity app or common depending on the supported account type selected when you created the identity provider app. To decide which value to assign, follow these criteria:

      • If you selected either Accounts in this organizational directory only (Microsoft only - Single tenant) or Accounts in any organizational directory (Any Microsoft Entra ID tenant - Multitenant), enter the tenant ID you recorded earlier for the Microsoft Entra app. This will be the tenant associated with the users who can be authenticated.

      • If you selected Accounts in any organizational directory (Any Microsoft Entra ID tenant - Multitenant) and personal Microsoft accounts (e.g. Skype, Xbox) enter the word common instead of a tenant ID. Otherwise, the Microsoft Entra app verifies through the tenant whose ID was selected and exclude personal Microsoft accounts.

    h. For Resource URL, enter https://graph.microsoft.com/. This URL isn't used in the code sample.
    i. Leave Scopes blank. The following image is an example:

    Screenshot shows how to add Teams bot auth bot identity connection adv1.

  6. Select Save.

Microsoft Azure Active Directory (Azure AD) v2

  1. In the Azure portal, select your Azure Bot from the dashboard.

  2. In the resource page, select Configuration under Settings.

  3. Select Add OAuth Connection Settings.
    The following image displays the corresponding selection in the resource page:

    Screenshot shows the corresponding selection in the resource page.

  4. Complete the form as follows:

    1. Name. Enter a name for the connection. Use this name in your bot in the appsettings.json file. For example, BotTeamsAuthADv2.

    2. Service Provider. Select Azure Active Directory v2. Once you select this option, the Azure AD v2 specific fields are displayed.

    3. Client id. Enter the Application (client) ID that you recorded for your Azure identity provider app.

    4. Client secret. Enter the secret that you recorded for your Azure identity provider app.

    5. Token Exchange URL. Leave this blank.

    6. Tenant ID, enter the Directory (tenant) ID that you recorded earlier for your Azure identity app or common depending on the supported account type selected when you created the identity provider app. To decide which value to assign, follow these criteria:

      • If you selected either Accounts in this organizational directory only (Microsoft only - Single tenant) or Accounts in any organizational directory (Any Microsoft Entra ID tenant - Multitenant), enter the tenant ID you recorded earlier for the Microsoft Entra app. This will be the tenant associated with the users who can be authenticated.

      • If you selected Accounts in any organizational directory (Any Microsoft Entra ID tenant - Multitenant) and personal Microsoft accounts (e.g. Skype, Xbox) enter the word common instead of a tenant ID. Otherwise, the Microsoft Entra app verifies through the tenant whose ID was selected and exclude personal Microsoft accounts.

    7. For Scopes, enter a space-delimited list of graph permissions this application requires, such as User.Read, User.ReadBasic.All, or Mail.Read.

  5. Select Save.

Test the connection

  1. Select the connection entry to open the connection you created.

  2. Select Test Connection at the top of the Service Provider Connection Setting panel.

  3. For the first time, it opens a new browser window asking you to select an account. Select the one you want to use.

  4. Next, allow to the identity provider to use your data (credentials). The following image is an example:

    The screenshot shows how to add Teams bot auth connection string adv1.

  5. Select Accept.

  6. A Test Connection to <your-connection-name> Succeeded page opens. Refresh the page if you get an error. The following image is an example:

    The screenshot shows how to add Teams app auth connection string adv1.

The bot code uses the connection name to retrieve user authentication tokens.

Prepare the bot sample code

With the preliminary settings done, let's focus on the creation of the bot to use in this article.

  1. Clone cs-auth-sample.

  2. Open Visual Studio.

  3. From the toolbar, select File > Open > Project/Solution and open the bot project.

  4. In C#, Update appsettings.json as follows:

    • Set ConnectionName to the name of the identity provider connection you added to the bot registration. The name we used in this example is BotTeamsAuthADv1.
    • Set MicrosoftAppId to the bot App ID you saved at the time of the bot registration.
    • Set MicrosoftAppPassword to the customer secret you saved at the time of the bot registration.

    Depending on the characters in your bot secret, you might need to XML escape the password. For example, any ampersands (&) must be encoded as &amp;.

    {
      "MicrosoftAppType": "",
      "MicrosoftAppId": "",
      "MicrosoftAppPassword": "",
      "ConnectionName": "",
    
  5. In the Solution Explorer, go to the TeamsAppManifest folder, open manifest.json and set id and botId to the bot App ID you saved at the time of the bot registration. For more information, see app manifest.

Deploy the bot to Azure

To deploy the bot, follow the steps in the How to Deploy your bot to Azure.

Alternatively, while in Visual Studio, you can follow these steps:

  1. In Visual Studio Solution Explorer, select and hold (or right-click) the project name.

  2. In the dropdown menu, select Publish.

  3. In the displayed window, select the New link.

  4. In the dialog window, select App Service and Create New.

  5. Select the Publish button.

  6. In the next dialog window, enter the required information.

    Screenshot shows how to enter required information for auth app service.

  7. Select Create.

  8. If the deployment completes successfully, you should see it reflected in Visual Studio. A page opens in your default browser with the message Your bot is ready!. The URL is similar to https://botteamsauth.azurewebsites.net/. Save it to a file.

  9. In your browser, go to the Azure portal.

  10. Check your resource group, the bot is listed along with the other resources. The following image is an example:

    Screenshot shows how to check resource group and bot.

  11. In the resource group, select the bot registration name (link).

  12. In the left panel, select Settings.

  13. In the Messaging endpoint box, enter the URL you just obtained followed by api/messages. For example, https://botteamsauth.azurewebsites.net/api/messages.

    Note

    Only one messaging endpoint is allowed for a bot.

  14. Select the Save button in the upper left.

Test the bot using the Emulator

Install Microsoft Bot Framework Emulator. For more information, see test and debug with the Emulator.

In order for the bot sample sign-in to work, you must configure the Emulator.

Configure the Emulator for authentication

If a bot requires authentication, you must configure the Emulator. To configure:

  1. Start the Emulator.
  2. In the Emulator, select the gear icon βš™ in the bottom left, or the Emulator Settings tab in the upper right.
  3. Check the box by Use version 1.0 authentication tokens.
  4. Enter the local path to the ngrok tool. See the Bot Framework Emulator / ngrok tunneling integration Wiki. For more tool information, see ngrok.
  5. Check the box by Run ngrok when the Emulator starts up.
  6. Select the Save button.

When the bot displays a sign-in card and the user selects the sign-in button, the Emulator opens a page that the user can use to sign in with the authentication provider. Once the user does so, the provider generates a user token and sends it to the bot. After that, the bot can act on behalf of the user.

Test the bot locally

After you configure the authentication mechanism, you can perform the actual bot testing.

  1. Run the bot sample locally on your machine, via Visual Studio for example.

  2. Start the Emulator.

  3. Select the Open bot button.

  4. In the Bot URL, enter the bot's local URL. Usually, http://localhost:3978/api/messages.

  5. In the Microsoft App ID, enter the bot's app ID from appsettings.json.

  6. In the Microsoft App password, enter the bot's app password from the appsettings.json.

  7. Select Connect.

  8. After the bot is up and running, enter any text to display the sign-in card.

  9. Select the Sign in button.

  10. A pop-up dialog appears to Confirm Open URL to authenticate the bot's user (you).

  11. Select Confirm.

  12. If asked, select the applicable user's account.

  13. Depending which configuration you used for the Emulator, you get one of the following options:

    1. Using sign-in verification code
      βœ“ A window opens displaying the validation code.
      βœ“ Copy and enter the validation code into the chat box to complete the sign-in.
    2. Using authentication tokens.
      βœ“ You're signed in based on your credentials.

    The following image is an example of the bot UI after you sign in:

    Screenshot shows an example of the bot UI after you sign in.

  14. If you select Yes when the bot asks Would you like to view your token?, you get the following response:

    Screenshot shows how to select the consent.

  15. Enter logout in the input chat box to sign out. It releases the user token, and the bot won't be able to act on your behalf until you sign in again.

Note

Bot authentication requires use of the Bot Connector Service. The service accesses the bots registration information for your bot.

Test the deployed bot

  1. In your browser, go to the Azure portal.

  2. Find your resource group.

  3. Select the resource link. The resource page is displayed.

  4. In the resource page, select Test in Web Chat. The bot starts and displays the predefined greetings.

  5. Type anything in the chat box.

  6. Select the Sign in box.

  7. A pop-up dialog appears to Confirm Open URL to authenticate the bot's user (you).

  8. Select Confirm.

  9. If asked, select the applicable user's account. The following image is an example of the bot UI after you sign in:

    Screenshot shows an example of the Teams bot UI after you sign in.

  10. Select the Yes button to display your authentication token. The following image is an example:

    Screenshot shows how to select Yes button to display your authentication token.

  11. Enter logout in the input chat box to sign out.

    Screenshot shows how to sign out of the bot.

Note

If you're having problems signing in, try to test the connection again as described in the previous steps. This could recreate the authentication token. With the Bot Framework Web Chat client in Azure, you may need to sign in several times before the authentication is established correctly.

Install and test the bot in Teams

  1. In your bot project, ensure that the TeamsAppManifest folder contains the manifest.json along with an outline.png and color.png files.

  2. In Solution Explorer, go to the TeamsAppManifest folder. Edit manifest.json by assigning the following values:

    1. Ensure that the bot App ID you received at the time of the bot registration is assigned to id and botId.
    2. Assign this value: validDomains: [ "token.botframework.com" ].
  3. Select and zip the manifest.json, outline.png, and color.png files.

  4. Open Microsoft Teams.

  5. In the left panel, at the bottom, select the Apps icon.

  6. In the right panel, at the bottom, select Upload a custom app.

  7. Go to the TeamsAppManifest folder and upload the zipped manifest. The following window appears:

    Screenshot shows an example of the bot after it's uploaded into Teams.

  8. Select the Add to a team button.

  9. In the next window, select the team where you want to use the bot.

  10. Select the Set up a bot button.

  11. Select the three dots (●●●) in the left panel. Then select the Developer Portal icon.

  12. Select the Manifest editor tab. You should see the icon for the bot you uploaded.

  13. Also, you should be able to see the bot listed as a contact in the chat list that you can use to exchange messages with the bot.

Testing the bot locally in Teams

Teams is an entirely cloud-based product. It requires all services it accesses to be available from the cloud using HTTPS endpoints. Therefore, to enable the bot (our sample) to work in Teams, you need to either publish the code to the cloud of your choice, or make a locally running instance externally accessible via a tunneling tool. We recommend ngrok, which creates an externally addressable URL for a port you open locally on your machine. To set up ngrok in preparation for running your Teams app locally, follow these steps:

  1. In a terminal window, go the directory where you have ngrok.exe installed. We suggest setting the environment variable path to point to it.

  2. Run, for example, ngrok http 3978 --host-header=localhost:3978. Replace the port number as needed. It launches ngrok to listen on the port you specify. In return, it gives you an externally addressable URL, valid for as long as ngrok is running. The following image is an example:

    Screenshot shows the Teams bot app auth connection string adv1

  3. Copy the forwarding HTTPS address that is similar to: https://dea822bf.ngrok.io/.

  4. Append /api/messages to obtain https://dea822bf.ngrok.io/api/messages, which is the messages endpoint for the bot running locally on your machine and reachable over the web in a chat in Teams.

  5. One final step to perform is to update the messages endpoint of the deployed bot. In the example, we deployed the bot in Azure. So let's perform these steps:

    1. In your browser, go to the Azure portal.
    2. Select your Bot Registration.
    3. In the left panel, select Settings.
    4. In the right panel, in the Messaging endpoint box, enter the ngrok URL, in our example, https://dea822bf.ngrok.io/api/messages.
  6. Start your bot locally, for example in Visual Studio debug mode.

  7. Test the bot while running locally using the Bot Framework portal's Test Web chat. Like the Emulator, this test doesn't allow you to access Teams-specific functionality.

  8. In the terminal window where ngrok is running you can see HTTP traffic between the bot and the web chat client. If you want a more detailed view, in a browser window enter http://127.0.0.1:4040 you obtained from the previous terminal window. The following image is an example:

    Screenshot shows auth bot teams ngrok testing.

Note

If you stop and restart ngrok, the URL changes. To use ngrok in your project, and depending on the capabilities you're using, you must update all URL references.

Additional information

TeamsAppManifest/manifest.json

This manifest contains information needed by Teams to connect with the bot:

{
  "$schema": "https://developer.microsoft.com/json-schemas/teams/v1.8/MicrosoftTeams.schema.json",
  "manifestVersion": "1.5",
  "version": "1.0.0",
  "id": "",
  "developer": {
    "name": "TeamsBotAuth",
    "websiteUrl": "https://www.microsoft.com",
    "privacyUrl": "https://www.teams.com/privacy",
    "termsOfUseUrl": "https://www.teams.com/termsofuse"
  },
  "icons": {
    "color": "color.png",
    "outline": "outline.png"
  },
  "name": {
    "short": "TeamsBotAuth",
    "full": "Teams Bot Authentication"
  },
  "description": {
    "short": "TeamsBotAuth",
    "full": "Teams Bot Authentication"
  },
  "accentColor": "#FFFFFF",
  "bots": [
    {
      "botId": "",
      "scopes": [
        "groupchat",
        "team"
      ],
      "supportsFiles": false,
      "isNotificationOnly": false
    }
  ],
  "permissions": [
    "identity",
    "messageTeamMembers"
  ],
  "validDomains": [ "token.botframework.com" ]
}

With authentication, Teams behaves differently than other channels.

Handling Invoke Activity

An Invoke Activity is sent to the bot rather than the Event Activity used by other channels, which is done by subclassing the ActivityHandler.

Bots/DialogBot.cs

    public class DialogBot<T> : TeamsActivityHandler where T : Dialog
    {
        protected readonly BotState ConversationState;
        protected readonly Dialog Dialog;
        protected readonly ILogger Logger;
        protected readonly BotState UserState;

        public DialogBot(ConversationState conversationState, UserState userState, T dialog, ILogger<DialogBot<T>> logger)
        {
            ConversationState = conversationState;
            UserState = userState;
            Dialog = dialog;
            Logger = logger;
        }

        public override async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
        {
            await base.OnTurnAsync(turnContext, cancellationToken);

            // Save any state changes that might have occurred during the turn.
            await ConversationState.SaveChangesAsync(turnContext, false, cancellationToken);
            await UserState.SaveChangesAsync(turnContext, false, cancellationToken);
        }

        protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            Logger.LogInformation("Running dialog with Message Activity.");

            // Run the Dialog with the new message Activity.
            await Dialog.RunAsync(turnContext, ConversationState.CreateProperty<DialogState>(nameof(DialogState)), cancellationToken);
        }
    }
}

Bots/TeamsBot.cs

The Invoke Activity must be forwarded to the dialog if the OAuthPrompt is used.

protected override async Task OnTeamsSigninVerifyStateAsync(ITurnContext<IInvokeActivity> turnContext, CancellationToken cancellationToken)
{
    Logger.LogInformation("Running dialog with signin/verifystate from an Invoke Activity.");

    // The OAuth Prompt needs to see the Invoke Activity in order to complete the login process.

    // Run the Dialog with the new Invoke Activity.
    await Dialog.RunAsync(turnContext, ConversationState.CreateProperty<DialogState>(nameof(DialogState)), cancellationToken);
}

TeamsActivityHandler.cs


protected virtual Task OnInvokeActivityAsync(ITurnContext<IInvokeActivity> turnContext, CancellationToken cancellationToken)
{
    switch (turnContext.Activity.Name)
    {
        case "signin/verifyState":
            return OnSigninVerifyStateAsync(turnContext, cancellationToken);

        default:
            return Task.CompletedTask;
    }
}

protected virtual Task OnSigninVerifyStateAsync(ITurnContext<IInvokeActivity> turnContext, CancellationToken cancellationToken)
{
    return Task.CompletedTask;
}

Code sample

This section provides Bot authentication v3 SDK sample.

Sample name Description .NET Node.js Python Manifest
Bot authentication This sample shows how to get started with authentication in a bot for Teams. View View View View
Tab, Bot, and Message Extension (ME) SSO This sample shows Microsoft Entra SSO for Tab, Bot, and ME - search, action, link-unfurling. View View NA View

See also