Chat Bot With Azure Authentication - Part One

Highlights of the article series

  • How to register an app with Azure Active Directory?
  • How to get the access token using Azure Active Directory authentication?
  • How to register a bot application with Azure Bot Service?
  • How to user Bot State Service to save user conversation state data such as access token?

Prerequisites

You can pull the code from GitHub.

Initial Setup

Step 1 Register an app with Azure Active Directory

Before going to Azure portal, let's create a web application for managing tokens post authentication process. Create a new project in Visual Studio with ASP .NET Web Application project template. In the next step, select MVC as web app template.

Select web application project and press F4. It will display Properties window. Change the "SSL Enabled" property to true. Make note of SSL URL; it will be required while registering the app. It will be used while registering an app.

Go to Azure Portal and login to your account. It will open your dashboard and on the left-hand side menu bar, there is Azure Active Directory option. Click on that option. It will open the tool pane for Active Directory configurations.

 

Click on "App Registrations" menu link. It will list down all the applications which are registered previously with Azure Active Directory. You can search apps by ID or the name of the app.

To register a new app, click on "New application registration" link. Enter the name for an app and provide SSL URL of your web application created above.
 
Now, click on the app. It will redirect you to the Settings page of the app. Note down the Application ID. Click on Required Permissions menu link and grant permissions to provide access to Azure Active Directory. To see what all permissions are granted, you can click on Permissions and it will open the list. Now, go to Keys menu and add a new key as ClientSecret which will be used while calling the token endpoint for requesting the access token.

 

Now, we are ready with app registration and permission.

Step 2 Update web application to handle pre and post authentication functionality

Add LoggedinToAzureAD.cshtml under Views folder.
  1. @{  
  2. ViewBag.Title = "Login Success";  
  3. }  
  4. <div class="jumbotron">  
  5.    <p class="lead">Login successful! Continue with chat..</p>  
  6. </div>  
Open HomeController.cs and add the LoginWithAzure() and LoggedinToAzureAD() methods.
  1. public ActionResult LoginWithAzure(string channelId, string userId)  
  2. {  
  3.     /// Save Channel Id and User Id to session  
  4.     Session["channelId"] = channelId;  
  5.     Session["userId"] = userId;  
  6.   
  7.     string tenantId = "8c3dad1d-xxxx-4f8b-xxxx-8263372eced6";  
  8.     string clientId = "5e9569bf-xxxx-418d-xxxx-fd33a25b9267";
  9.   
  10.     string redirect_uri = $"https://localhost:44332/HOME/LoggedinToAzureAD";  
  11.   
  12.     string url = $"https://login.microsoftonline.com/{tenantId}/oauth2/authorize?client_id={clientId}&response_type=code&redirect_uri={redirect_uri}";  
  13.   
  14.     /// Redirect to login page  
  15.     return Redirect(url);  
  16. }  
Whenever a user tries to login, the user will be redirected to LoginWithAzure view. In Controller for LoginWithAzure view, first, we are saving channel id and user id in the session. Then, we prepare URL for Azure login with parameters like tenant id, client id, and redirect URI. We have specified the URL of LoggedinToAzureAD view as redirect URI. After successful login, Azure will make post call to the redirect URI with authorization code as a query string parameter.
  1. public ActionResult LoggedinToAzureAD()  
  2.       {  
  3.           string authorizationcode = Convert.ToString(this.Request.QueryString["code"]);  
  4.   
  5.           string tenantId = "8c3dad1d-xxxx-xxxx-xxxx-xxxxxxxxxxxx";  
  6.           string clientId = "xxxxxxxx-54cd-xxxx-942e-b38145646559";  
  7.           string clientSecret = "3VRAK0EetjxxxxxxxxxxxxxxxxxqURLMzY60lM=";  
  8.           string appresourceId = "https://graph.windows.net/";  
  9.           string redirect_uri = "https://localhost:44332/HOME/LoggedinToAzureAD";  
  10.   
  11.           //Build the URI  
  12.           var builder = new UriBuilder($"https://login.microsoftonline.com/{tenantId}/oauth2/token");  
  13.   
  14.           NameValueCollection postBody = new NameValueCollection(){  
  15.               { "client_id", $"{clientId}" }, { "client_secret", $"{clientSecret}" },  
  16.               { "grant_type""authorization_code" }, { "code", $"{authorizationcode}" },  
  17.               { "redirect_uri", $"{redirect_uri}"}, { "resource", $"{appresourceId}" }  
  18.           };  
  19.   
  20.           //Send the POST request  
  21.           using (WebClient client = new WebClient())  
  22.           {  
  23.               var responseString = System.Text.Encoding.UTF8.GetString(client.UploadValues(builder.Uri, postBody));  
  24.               JObject json = JObject.Parse(responseString);  
  25.               string accessToken = Convert.ToString(json["access_token"]);  
  26.               StateClient stateClient = new StateClient(new MicrosoftAppCredentials("bot application id""bot app password"));  
  27.               BotData userData = stateClient.BotState.GetUserData(Convert.ToString(Session["channelId"]), Convert.ToString(Session["userId"]));  
  28.               userData.SetProperty<string>("AccessToken", accessToken);  
  29.               stateClient.BotState.SetUserData(Convert.ToString(Session["channelId"]), Convert.ToString(Session["userId"]), userData);  
  30.           }  
  31.           return View();  
  32.       }  
As we have mentioned the URL of LoggedinToAzure view as redirect URI, after login, Azure will redirect the user to LoggedinToAzure view with authorization code as query string parameter. We will call the token endpoint to get the access token by sending client id, client secret, and resource as Graph API resource URL. We will make POST call to token endpoint using WebClient. It will return an access token. We will save this access token to the Bot State Service for selected channel and user id. To access the Bot State Service, we will use the app id and app password which we get while registering a bot application.
 
We are ready with the initial setup of Azure Active Directory and Authentication Web App. We will discuss how to register a bot and the usage of bot state service in next article of this series. Until then, keep creating chat bots.


Similar Articles