Add authentication to your bot via Azure Bot Service

APPLIES TO: yesSDK v4 no SDK v3

The Azure Bot Service and the v4 SDK include new bot authentication capabilities, providing features to make it easier to develop a bot that authenticates users to various identity providers, such as Azure AD (Azure Active Directory), GitHub, Uber, and so on. These capabilities can improve the user experience by eliminating the magic code verification for some clients.

Prior to this, your bot needed to include OAuth controllers and login links, store the target client IDs and secrets, and perform user token management. The bot would ask the user sign in on a website, which would then generate a magic code the user could use to verify their identity.

Now, bot developers no longer need to host OAuth controllers or manage the token life-cycle, as all of this can now be done by the Azure Bot Service.

The features include:

  • Improvements to the channels to support new authentication features, such as new WebChat and DirectLineJS libraries to eliminate the need for the 6-digit magic code verification.
  • Improvements to the Azure Portal to add, delete, and configure connection settings to various OAuth identity providers.
  • Support for a variety of out-of-the-box identity providers including Azure AD (both v1 and v2 endpoints), GitHub, and others.
  • Updates to the C# and Node.js Bot Framework SDKs to be able to retrieve tokens, create OAuthCards and handle TokenResponse events.
  • Samples for how to make a bot that authenticates to Azure AD.

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

You can extrapolate from the steps in this article to add such features to an existing bot. These sample bots demonstrate the new authentication features.


The authentication features also work with BotBuilder v3. However, this article covers just the v4 sample code.

About this sample

You need to create an Azure bot resource, and you need:

  1. An Azure AD app registration to allow your bot to access an external resource, such as Office 365.
  2. A separate bot resource. The bot resource registers your bot's credentials, and you need these credentials to test the authentication features, even when running your bot code locally.


Whenever you register a bot in Azure, it gets assigned an Azure AD app. However, this app secures channel-to-bot access. You need an additional AAD app for each application that you want the bot to be able to authenticate on behalf of the user.

This article describes a sample bot that connects to the Microsoft Graph using an Azure AD v1 or v2 token. It also covers how to create and register the associated Azure AD app. As part of this process, you'll use code from the Microsoft/BotBuilder-Samples GitHub repo. This article covers these processes.

  • Create your bot resource
  • Create an Azure AD application
  • Register your Azure AD application with your bot
  • Prepare the bot sample code

Once you finish, you will have a bot running locally that can respond to a few simple tasks against an Azure AD application, such as checking and sending an email, or displaying who you are and who your manager is. To do this, your bot will use a token from an Azure AD application against the Microsoft.Graph library. You do not need to publish your bot to test the OAuth sign-in features; however, your bot will need a valid Azure app ID and password.

These authentication features work with other types of bots, too. However, this article uses a registration-only bot.

Web Chat and Direct Line considerations

There are a couple of important security issues to consider when you use Azure Bot Service authentication with Web Chat.

  1. Prevent impersonation, where an attacker makes the bot think they're someone else. In Web Chat, an attacker can impersonate someone else by changing the user ID of his Web Chat instance.

    To prevent this, make the user ID unguessable. When you enable enhanced authentication options in the Direct Line channel, Azure Bot Service can detect and reject any user ID change. The user ID on messages from Direct Line to your bot will always be the same as the one you initialized Web Chat with. Note that this feature requires the user ID to start with dl_.

  2. Ensure the correct user is signed in. The user has two identities: their identity in a channel and their identity with the identity provider. In Web Chat, Azure Bot Service can guarantee that the sign-in process is completed in the same browser session as Web Chat itself.

    To enable this protection, start Web Chat with a Direct Line token that contains a list of trusted domains that can host the bot's Web Chat client. Then, statically specify the trusted domain (origin) list in the Direct Line configuration page.


Sample BotBuilder version Demonstrates
Bot authentication in CSharp or JavaScript v4 OAuthCard support
Bot authentication MSGraph in CSharp or JavaScript v4 Microsoft Graph API support with OAuth 2

Create your bot resource on Azure

Create a Bot Channels Registration using the Azure Portal.

Record your bot's app ID and password. To gather this information, see Manage a bot.

Create and register an Azure AD application

You need an Azure AD application that your bot can use to connect to the Microsoft Graph API.

For this bot you can use Azure AD v1 or v2 endpoints. For information about the differences between the v1 and v2 endpoints, see the v1-v2 comparison and the Azure AD v2.0 endpoint overview.

Create your Azure AD application

Use these steps to create a new Azure AD application. You can use the v1 or v2 endpoints with the app that you create.


You will need to create and register the Azure AD application in a tenant in which you can consent to delegate permissions requested by an application.

  1. Open the Azure Active Directory panel in the Azure portal. If you are not in the correct tenant, click Switch directory to switch to the correct tenant. (For instruction on creating a tenant, see Access the portal and create a tenant.)

  2. Open the App registrations panel.

  3. In the App registrations panel, click New registration.

  4. Fill in the required fields and create the app registration.

    1. Name your application.

    2. Select the Supported account types for your application. (Any of these options will work with this sample.)

    3. For the Redirect URI

      1. Select Web.
      2. Set the URL to
    4. Click Register.

      • Once it is created, Azure displays the Overview page for the app.
      • Record the Application (client) ID value. You will use this value later as the Client id when you register your Azure AD application with your bot.
      • Also record the Directory (tenant) ID value. You will also use this to register this application with your bot.
  5. In the navigation pane, click Certificates & secrets to create a secret for your application.

    1. Under Client secrets, click New client secret.
    2. Add a description to identify this secret from others you might need to create for this app, such as bot login.
    3. Set Expires to Never.
    4. Click Add.
    5. Before leaving this page, record the secret. You will use this value later as the Client secret when you register your Azure AD application with your bot.
  6. In the navigation pane, click API permissions to open the API permissions panel. It is a best practice to explicitly set the API permissions for the app.

    1. Click Add a permission to show the Request API permissions pane.

    2. For this sample, select Microsoft APIs and Microsoft Graph.

    3. Choose Delegated permissions and make sure the permissions you need are selected. This sample requires theses permissions.


      Any permission marked as ADMIN CONSENT REQUIRED will require both a user and a tenant admin to login, so for your bot tend to stay away from these.

      • openid
      • profile
      • Mail.Read
      • Mail.Send
      • User.Read
      • User.ReadBasic.All
    4. Click Add permissions. (The first time a user accesses this app through the bot, they will need to grant consent.)

You now have an Azure AD application configured.

Register your Azure AD application with your bot

The next step is to register with your bot the Azure AD application that you just created.

  1. Navigate to your bot's resource page on the Azure Portal.

  2. Click Settings.

  3. Under OAuth Connection Settings near the bottom of the page, click Add Setting.

  4. Fill in the form as follows:

    1. For Name, enter a name for your connection. You'll use this name in your bot code.

    2. For Service Provider, select Azure Active Directory. Once you select this, the Azure AD-specific fields will be displayed.

    3. For Client id, enter the application (client) ID that you recorded for your Azure AD v1 application.

    4. For Client secret, enter the secret that you created to grant the bot access to the Azure AD app.

    5. For Grant Type, enter authorization_code.

    6. For Login URL, enter

    7. For Tenant ID, enter the directory (tenant) ID that your recorded earlier for your Azure AD app.

      This will be the tenant associated with the users who can be authenticated.

    8. For Resource URL, enter

    9. Leave Scopes blank.

  5. Click Save.


These values enable your application to access Office 365 data via the Microsoft Graph API.

Test your connection

  1. Click on the connection entry to open the connection you just created.
  2. Click Test Connection at the top of the Service Provider Connection Setting pane.
  3. The first time, this should open a new browser tab listing the permissions your app is requesting and prompt you to accept.
  4. Click Accept.
  5. This should then redirect you to a Test Connection to <your-connection-name> Succeeded page.

You can now use this connection name in your bot code to retrieve user tokens.

Prepare the bot code

You will need your bot's app ID and password to complete this process.

  1. Clone from the github repository the sample you want to work with: Bot authentication or Bot authentication MSGraph.

  2. Update appsettings.json:

    • Set ConnectionName to the name of the OAuth connection setting you added to your bot.

    • Set MicrosoftAppId and MicrosoftAppPassword to your bot's app ID and app secret.

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

      "MicrosoftAppId": "",
      "MicrosoftAppPassword": "",
      "ConnectionName": ""

If you do not know how to get your Microsoft app ID and Microsoft app password values, you can create a new password as described here


You could now publish this bot code to your Azure subscription (right-click on the project and choose Publish), but it is not necessary for this article. You would need to set up a publishing configuration that uses the application and hosting plan that you used when configuration the bot in the Azure Portal.

Test the bot

  1. If you have not done so already, install the Bot Framework Emulator.

  2. Run the sample locally on your machine.

  3. Start the emulator, connect to your bot, and send messages.

    • You will need to provide your bot's app ID and password when you connect to your bot.

      • If you needed to XML-escape the password in your bot code, you also need to do so here.
    • Type help to see a list of available commands for the bot, and test the authentication features.

    • Once you've signed in, you don't need to provide your credentials again until you sign out.

    • To sign out, and cancel your authentication, type logout.


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

In the Bot authentication sample, the dialog is designed to retrieve the user token after the user is logged in.

Sample output

Additional information

When a user asks the bot to do something that requires the bot to have the user logged in, the bot can use an OAuthPrompt to initiate retrieving a token for a given connection. The OAuthPrompt creates a token retrieval flow that consists of:

  1. Checking to see if the Azure Bot Service already has a token for the current user and connection. If there is a token, the token is returned.
  2. If Azure Bot Service does not have a cached token, an OAuthCard is created which is a sign in button the user can click on.
  3. After the user clicks on the OAuthCard sign in button, Azure Bot Service will either send the bot the user's token directly or will present the user with a 6-digit authentication code to enter in the chat window.
  4. If the user is presented with an authentication code, the bot then exchanges this authentication code for the user's token.

The following sections describe how the sample implements some common authentication tasks.

Use an OAuth prompt to sign the user in and get a token

Bot architecture


Add an OAuth prompt to MainDialog in its constructor. Here, the value for the connection name was retrieved from the appsettings.json file.

AddDialog(new OAuthPrompt(
    new OAuthPromptSettings
        ConnectionName = ConnectionName,
        Text = "Please Sign In",
        Title = "Sign In",
        Timeout = 300000, // User has 5 minutes to login (1000 * 60 * 5)

Within a dialog step, use BeginDialogAsync to start the OAuth prompt, which asks the user to sign in.

  • If the user is already signed in, this will generate a token response event, without prompting the user.
  • Otherwise, this will prompt the user to sign in. The Azure Bot Service sends the token response event after the user attempts to sign in.
return await stepContext.BeginDialogAsync(nameof(OAuthPrompt), null, cancellationToken);

Within the following dialog step, check for the presence of a token in the result from the previous step. If it is not null, the user successfully signed in.

// 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.
var tokenResponse = (TokenResponse)stepContext.Result;
if (tokenResponse != null)

Wait for a TokenResponseEvent

When you start an OAuth prompt, it waits for a token response event, from which it will retrieve the user's token.


AuthBot derives from ActivityHandler and explicitly handles token response event activities. Here, we continue the active dialog, which allows the OAuth prompt to process the event and retrieve the token.

protected override async Task OnTokenResponseEventAsync(ITurnContext<IEventActivity> turnContext, CancellationToken cancellationToken)
    Logger.LogInformation("Running dialog with Token Response Event Activity.");

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

Log the user out

It's best practice to let users explicitly sign out or logout, instead of relying on the connection to time out.


protected string ConnectionName { get; }

protected override async Task<DialogTurnResult> OnBeginDialogAsync(DialogContext innerDc, object options, CancellationToken cancellationToken = default(CancellationToken))
    var result = await InterruptAsync(innerDc, cancellationToken);
    if (result != null)
        return result;

    return await base.OnBeginDialogAsync(innerDc, options, cancellationToken);

protected override async Task<DialogTurnResult> OnContinueDialogAsync(DialogContext innerDc, CancellationToken cancellationToken = default(CancellationToken))
    var result = await InterruptAsync(innerDc, cancellationToken);
    if (result != null)
        return result;

    return await base.OnContinueDialogAsync(innerDc, cancellationToken);

private async Task<DialogTurnResult> InterruptAsync(DialogContext innerDc, CancellationToken cancellationToken = default(CancellationToken))
    if (innerDc.Context.Activity.Type == ActivityTypes.Message)
        var text = innerDc.Context.Activity.Text.ToLowerInvariant();

        if (text == "logout")
            // The bot adapter encapsulates the authentication processes.
            var botAdapter = (BotFrameworkAdapter)innerDc.Context.Adapter;
            await botAdapter.SignOutUserAsync(innerDc.Context, ConnectionName, null, cancellationToken);
            await innerDc.Context.SendActivityAsync(MessageFactory.Text("You have been signed out."), cancellationToken);
            return await innerDc.CancelAllDialogsAsync(cancellationToken);

    return null;

Further reading