Build a bot with SSO authentication
Microsoft Teams bots are conversational bots that run repetitive automated tasks done by the users, such as customer service. The user needs to sign in multiple times without single sign-on (SSO) authentication. With SSO authentication methods, the users don't need to sign in to the bot multiple times.
A bot behaves differently depending on the conversation it's involved in:
- Bots in channel and group chat conversations require the users to @mention the bot.
- Bots in a one-to-one conversation don't require an @mention. All messages sent by the user routes to the bot.
This step-by-step guide helps you to build a bot with SSO authentication. You'll see the following output:
Prerequisites
Ensure you install the following tools and set up your development environment:
| Install | For using... | |
|---|---|---|
| Required | ||
| Microsoft Teams with an account (not a guest account) | Microsoft Teams to collaborate with everyone you work with through apps for chat, meetings, calls, and all in one place. | |
| Visual Studio 2022 version 17.3 Install one of the following two workloads: • ASP.NET and web development • .NET Core cross-platform development |
You can install the enterprise version in Visual Studio 2022, and install the workloads. | |
| Microsoft 365 developer account | Access to Teams account with the appropriate permissions to install an app. | |
| ngrok | Teams app features (conversational bots, message extensions, and incoming webhooks) require inbound connections. A tunnel connects your development system to Teams. It isn't required for apps that only include tabs. This package is installed within the project directory (using npm devDependencies). |
Note
After downloading ngrok, sign up and install authtoken.
Set up your Teams development tenant
A tenant is like a space or a container where you chat, share files, and run meetings for your organization in Teams. You can also sideload and test the app.
Check for sideloading option
After creating the app, you must load your app in Teams without distributing it. This loading is known as sideloading. Sign in to your Microsoft 365 account to view this option.
Note
Sideloading is necessary for previewing and testing apps in Teams local environment. Enable Sideloading to preview and test your app in Teams locally.
Do you already have a tenant, and do you have the admin access? Let's check if you really do!
To verify sideload apps in Teams:
In the Teams client, select Apps.
Select Manage your apps > Upload an app.
Look for the option Upload a custom app. If you see the option, sideloading apps is enabled.
Note
If you don't have the option to upload a custom app, contact Teams administrator.
Create a free Teams developer tenant (optional)
If you don't have a Teams developer account, you can get it free. Join the Microsoft 365 developer program!
Go to the Microsoft 365 developer program.
Select Join Now and follow the onscreen instructions.
Select Setup E5 subscription from the welcome screen.
Set up administrator account. After you finish, the following screen displays.
Sign in to Teams using the new administrator account. Now you should have the Upload a custom app option.
Create and register your bot
The following steps help you to create and register your bot in Microsoft Azure portal:
- Create Azure Bot resource to register bot with Azure Bot Service.
- Create client secret to enable SSO authentication of the bot.
- Add Teams channel to deploy the bot.
- Create a tunnel to your web server's endpoints by using ngrok.
- Add messaging endpoint to the ngrok tunnel you created.
To create Azure Bot resource
Go to the Azure portal.
Select Create a resource.
In the search box, enter Azure bot.
Select Enter.
Select Azure Bot.
Select Create.
The Create an Azure Bot window appears.
Enter the following details to create Azure bot.
Enter required bot handle name in Bot handle.
Select your Subscription and Resource group from the dropdown list.
To create a new resource group, select Create new > enter resource name > OK. Now, select the required location from New resource group location dropdown list.
Select Type of App as follows:
- Multi Tenant, if your bot is supported on multiple tenants.
- Single Tenant, if your bot is supported on a single tenant.
In the Microsoft App ID section, by default Create new Microsoft App ID is selected.
You can also select Use existing app registration and enter existing App ID, App tenant ID, and MSI resource ID.
Note
You can't create more than one bot with the same Microsoft App ID.
Select Review + create.
After the validation is passed, select Create.
It takes a few moments for your bot service to be provisioned.
Select Go to resource.
Your Azure bot is created. You can see the Resource group and Subscription ID details in the Azure bot.
To create client secret
Perform the following steps to create client secret:
In the left pane, select Configuration.
Tip
Save the Microsoft App ID or Client ID for future reference.
Next to Microsoft App ID, select Manage.
In the Client secrets section, select New client secret.
The Add a client secret window appears.
Enter Description.
Select Add.
In the Value column, select copy to clipboard icon to copy the value details.
Tip
Save the Client secrets value or app password for future reference.
Add bot to the Teams channel
Select Home.
Select your bot from Recent resources.
Select Channels in the left pane.
Select Microsoft Teams.
Select the checkbox to accept the Terms of Service.
Select Agree.
Select Apply.
To create tunnel for local web server
Use ngrok to create a tunnel to your locally running web server's publicly available HTTPS endpoints. Run the following command in ngrok:
ngrok http --host-header=localhost 3978
Tip
If you encounter ERR_NGROK_4018, follow the steps as displayed in the command prompt to sign up and authenticate ngrok. Then run the ngrok http --host-header=localhost 3978 command.
To add messaging endpoint
From ngrok, copy the HTTPS URL.
Note
The HTTPS URL in your ngrok is your fully qualified domain name. The
WebAppDomainis a fully qualified domain name that doesn't includehttps://in it.Go back to the Azure portal.
In Settings for the Azure bot that you created, select Configuration.
In Messaging endpoint, use the HTTPS URL available from ngrok and at the end of the URL add /api/messages.
Select Apply.
You have successfully set up a bot in Azure Bot Service.
Configure SSO for your bot
To add Redirect URI to the Azure bot resource
Select Home > Azure Active Directory.
From the left pane, select App registrations.
Select your bot.
From the left pane, select Authentication to set a redirect URI.
In Platform configurations, select Add a platform to choose the platform on which you want to host the bot app.
For this tutorial, select Web.
Enter Redirect URIs as
https://token.botframework.com/.auth/web/redirectand this URI on which Azure AD will send response for user authentication.Enable Implicit grant and hybrid flows by selecting the following checkboxes:
- ID tokens
- Access tokens
Select Configure.
The Redirect URI is added to the Azure bot resource.
To expose API endpoint
From the left pane, select Expose an API.
Select Set.
Set the Application ID URI in the form of
api://botid-{your AppID}.Select Save.
Note
- If you're using a tunneling service such as ngrok, ensure you update the value whenever your ngrok subdomain changes.
- For example:
api://f631****.ngrok.io/92c11075-c629-4a1e-ab58-02b4fd4204c2, wheref631****.ngrok.iois the new ngrok subdomain name.
Select Add a scope.
The Add a scope window appears.
Enter the details to configure scope.
Enter
access_as_useras the Scope name.Note
The Scope name should match with the Application ID URI with
/access_as_userappended at the end.Set Who can consent? to
Admins and users.To configure the admin and user consent prompts with appropriate values for
access_as_userscope, provide the following information in the fields:Enter
Teams can access the user’s profileas Admin consent display name.Enter
Allows Teams to call the app’s web APIs as the current useras Admin consent description.Enter
Teams can access the user profile and make requests on the user’s behalfas User consent display name.Enter
Enable Teams to call this app’s APIs with the same rights as you haveas User consent description.
Ensure that State is set to Enabled.
Select Add scope to save.
Your Application ID URI is created with Scope name.
In the Authorized client applications section, identify the applications that you want to authorize for your app’s web application.
Select Add a client application.
The Add a client application window appears.
Enter the Client ID for desktop and web application separately that you want to authorize. It's the application ID of client application that you want to authorize.
Client ID For authorizing 1fec8e78-bce4-4aaf-ab1b-5451cc387264Teams desktop or mobile application 5e3ce6c0-2b1f-4285-8d4b-75ee78787346Teams web application Select Authorized scopes to determine which type of token will be returned by the service.
Select Add application.
The following image displays the Client ID:
Configure Graph permissions
In the left pane, select API Permissions.
Note
Users need to consent to the API permissions only if the bot app is registered in a different tenant.
Select Add a permission.
The Request API permission window appears.
Select Microsoft Graph.
Select Delegated permissions.
Select User.Read permission from the User dropdown.
Select Add permissions.
To update manifest
From the left pane, select Manifest.
Ensure the config item is set to "accessTokenAcceptedVersion": 2. If not, change its value to 2 and select Save.
Note
If you're already testing your bot in Teams, you must sign out from this app and Teams. Then sign in again to see this change.
To set up Bot service connection
In Configuration page, select Add OAuth Connection Settings.
The New Connection Setting window appears.
In New Connection Setting, enter the following details:
Field Value or description Name Enter name for your new connection setting. You can use the name in the settings of your bot service code. Service Provider Select Azure Active Directory V2. Client id Saved previously as your Microsoft App ID. Client secret Saved previously as Value of the client secret ID. Token Exchange URL Use the Application ID URL obtained previously while exposing API endpoint. Tenant ID Enter common. If you're using a single tenant app registration, use the tenant ID of the tenant where the bot is registered. Scopes Enter User.Read and also add all the Scopes required while specifying permissions to downstream APIs.
Select Save.
You have now configured SSO for your bot.
Configure and run your bot sample
Open Visual Studio.
Select Clone a repository.
In the Repository location, enter
https://github.com/OfficeDev/Microsoft-Teams-Samples.git. Ensure that you note the Path where the repository is cloned.Go to File > Open > Project/Solution.
Select BotConversationSsoQuickstart.sln file from bot-conversation-sso-quickstart > csharp_dotnetcore folder.
Open the appsettings.json file from BotConversationSsoQuickstart folder.
Update the following in appsettings.json file:
{ "MicrosoftAppId": "{TODO: MicrosoftAppId}", "MicrosoftAppPassword": "{TODO: ClientSecret}", "ConnectionName": "{TODO: ConnectionName}", "MicrosoftAppType": "MultiTenant", // Set this to SingleTenant if you are using a single tenant app registration "MicrosoftAppTenantId": "common" // Set your tenantId here if you are using single tenant app registration. }- Update the
MicrosoftAppIdandMicrosoftAppPasswordfor your bot. You can obtain theMicrosoftAppIdfrom the bot's configuration page. TheMicrosoftAppPasswordis the value for client secret ID that you saved previously in Azure portal. - Update
MicrosoftAppTypeasMultiTenantif your bot is supported on multiple tenants. If your bot is supported on single tenant, updateMicrosoftAppTypeasSingleTenant. - Update
MicrosoftAppTenantIdascommonif you're using a multi-tenant app registration. If you're using a single tenant app registration, updatetenantIdas the value forMicrosoftAppTenantId. - Use the OAuth connection name as the Connection Name.
- Update the
Select F5 to run the project.
Select Yes if the following dialog appears:
A webpage opens with a message Bot is Ready.
Troubleshooting
If you get the Unable to find package error, follow these steps:
- Go to Tools > NuGet Package Manager > Package Manager Settings.
- In the Options window that appears, select NuGet Package Manager > Package Sources.
- Select Add.
- In Name, enter
nuget.organd in Source, enterhttps://api.nuget.org/v3/index.json. - Select Update and OK.
- Rebuild your project.
Configure and run the Teams app
In Visual Studio, open appPackage folder.
Open the manifest.json file.
Replace all occurrences of {TODO: MicrosoftAppId} with your bot's Microsoft App ID.
In your cloned repository, go to bot-conversation-sso-quickstart > csharp_dotnetcore > BotConversationSsoQuickstart > appPackage.
Create a .zip with the following files that are present in the appPackage folder:
- manifest.json
- icon-outline.png
- icon-color.png
Go to Microsoft Teams.
Select Apps > Manage your apps.
Select Upload an app and select Upload a custom app.
Select Open to upload the .zip file that you've created in the Manifest folder.
Select Add to add the bot to your chat.
You can interact with the bot by sending it a message. The bot exchanges an SSO token and calls the Graph API on your behalf. It keeps you signed in unless you send a message to sign out.
Send a message to the bot. The conversation bot asks for consent for the first time.
Select Continue to give permissions to Teams client for accessing the bot.
Note
Now you have configured SSO with your bot app and it's the only time you'll have to give consent.
For mobile device, select Accept for Permissions requested.
Note
Now you have configured SSO with your bot app in mobile, and this is the only time you'll have to give consent.
Complete challenge
Did you come up with something like this?
Congratulations!
You've completed the tutorial to get started with build a bot with SSO authentication.
Have an issue with this section? If so, please give us some feedback so we can improve this section.
Feedback
Submit and view feedback for