Silent Authentication in Azure Bot C#
Hi Team,
Could you please assist me with the following scenario?
Scenario:
We have a website with SSO enabled using the MSAL library. We aim to integrate a C# Azure bot into this website via an iframe, webchat, etc. The challenge is to have the bot automatically obtain the SSO token from the parent page (the website) without passing it manually from the website to the bot. Additionally, we want to avoid prompting the user to log in again within the chatbot.
Once silent authentication is completed, we also need to dynamically pass some custom data from the website to the bot.
Thanks
Azure AI Bot Service
-
navba-MSFT 24,890 Reputation points • Microsoft Employee
2024-07-22T06:44:01.7733333+00:00 @REDDY, REDDYVALLA NAVEENKUMAR Welcome to Microsoft Q&A Forum, Thank you for posting your query here!
.
.
To achieve silent authentication for your Azure bot integrated into a website with SSO enabled using the MSAL library, you can follow these steps:
- Configure Azure AD for SSO:
- Ensure your website is configured with Azure AD for Single Sign-On (SSO) using the MSAL library.
- Register your bot in Azure AD and configure the necessary permissions.
.
.
- Set Up the Bot for Authentication:
- Use the Bot Framework SDK to set up authentication for your bot. You can refer to the Bot Framework authentication documentation for detailed steps.
.
.
- Implement Silent Authentication:
- To achieve silent authentication, you can leverage the MSAL.js library on the client-side to acquire tokens silently. This involves using the acquireTokenSilent method to get the token without user interaction.
- Pass the acquired token to the bot via the Web Chat control or Direct Line. You can embed the Web Chat control in your website and configure it to pass the token to the bot.
.
.
- Pass Custom Data to the Bot:
- You can pass custom data from the parent page to the bot by including it in the Web Chat control’s configuration. For example, you can use the user property to pass additional information.
.
.
Sample code for client side:
// MSAL configuration const msalConfig = { auth: { clientId: "YOUR_CLIENT_ID", authority: "https://login.microsoftonline.com/YOUR_TENANT_ID", redirectUri: "YOUR_REDIRECT_URI" } }; const msalInstance = new msal.PublicClientApplication(msalConfig); // Silent token acquisition msalInstance.acquireTokenSilent({ scopes: ["YOUR_SCOPES"] }).then(response => { const token = response.accessToken; // Initialize Web Chat with the token window.WebChat.renderWebChat({ directLine: window.WebChat.createDirectLine({ token: "YOUR_DIRECT_LINE_TOKEN" }), userID: "USER_ID", username: "USERNAME", locale: "en-US", user: { id: "USER_ID", name: "USERNAME", token: token } }, document.getElementById('webchat')); }).catch(error => { console.error(error); });
. .
Server side code:
public class MyBot : ActivityHandler { protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken) { var token = turnContext.Activity.From.Properties["token"]?.ToString(); var customData = turnContext.Activity.From.Properties["customData"]?.ToString(); // Use the token and custom data as needed } }
.
.
More Resources:
- Refer the SilentAuth-Webchat code in GitHub. This project showcases the silent authentication features in Azure Bot Service.
- Adding Auth for Bot, refer this article.
- Silent auth in multi-tenant, refer this SO thread.
.
.
Hope this helps. If you have any follow-up questions, please let me know. I would be happy to help.
-
REDDY, REDDYVALLA NAVEENKUMAR 115 Reputation points
2024-07-22T07:00:36.5+00:00 Thanks for the response @navba-MSFT
The provided steps suggest passing the token to the bot; however, it is not allowed as per our policy to pass the token from the parent page to the bot. Instead, the bot should dynamically fetch the token internally utilizing SSO capabilities without prompting the user to log in again within the chatbot.
-
navba-MSFT 24,890 Reputation points • Microsoft Employee
2024-07-22T07:22:07.97+00:00 @REDDY, REDDYVALLA NAVEENKUMAR Thanks for clarifying.
I hope you have added a new connection setting with the necessary details (client ID, client secret, etc.) Under “Settings,” select “OAuth Connection Settings.” .
You could leverage the below sample snippet to acquire token silently and pass the custom user data dynamically:
public class SilentAuthBot : ActivityHandler { private readonly string _connectionName = "YOUR_OAUTH_CONNECTION_NAME"; protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken) { var tokenResponse = await GetTokenAsync(turnContext, cancellationToken); var customData = turnContext.Activity.Value?.ToString(); if (tokenResponse != null) { // Use the token to call APIs or perform actions await turnContext.SendActivityAsync(MessageFactory.Text($"Token acquired silently! Custom data: {customData}"), cancellationToken); } else { await turnContext.SendActivityAsync(MessageFactory.Text("Failed to acquire token."), cancellationToken); } } private async Task<TokenResponse> GetTokenAsync(ITurnContext turnContext, CancellationToken cancellationToken) { var userTokenClient = turnContext.TurnState.Get<UserTokenClient>(); return await userTokenClient.GetUserTokenAsync(turnContext, _connectionName, null, cancellationToken); } }
Refer the SSO article for bots: https://learn.microsoft.com/en-us/azure/bot-service/bot-builder-authentication-sso?view=azure-bot-service-4.0&tabs=eml
Hope this helps.
-
REDDY, REDDYVALLA NAVEENKUMAR 115 Reputation points
2024-07-22T07:42:06.8366667+00:00 Thanks for the response @navba-MSFT .
Does the above approach require any steps to be included in the client-side implementation?
and it works only for list of Service Provider mentioned in Azure right?
-
navba-MSFT 24,890 Reputation points • Microsoft Employee
2024-07-22T08:04:37.51+00:00 @REDDY, REDDYVALLA NAVEENKUMAR Thanks for getting back.
There are a few client-side considerations to ensure seamless integration:Here’s a brief overview of the client-side steps:
- Configure Web Chat: Ensure that the Web Chat control is configured to support authentication and can handle token exchange requests.
- Intercept OAuth Cards: Implement logic to intercept OAuth cards and handle token exchange requests.
- Send Custom Data: Ensure that custom data is included in the activity payload when initiating a conversation with the bot.there are a few client-side considerations to ensure seamless integration:
- Embedding the Bot: When embedding the bot in an iframe or webchat, ensure that the iframe or webchat control is properly configured to support authentication. This might involve setting up the iframe to allow the bot to access the necessary cookies or tokens.
- Token Exchange: Although your policy restricts passing the token directly, the bot can still initiate a token exchange process. The client-side application (your website) should be configured to handle token exchange requests from the bot. This involves intercepting OAuth cards and handling token exchange requests as described in the Bot Framework SSO documentation1.
- Custom Data Handling: To pass custom data dynamically, you can use the
Activity.Value
property in the bot framework. Ensure that the client-side application sends the necessary custom data within the activity payload when initiating a conversation with the bot.
Here’s a brief overview of the client-side steps:[Security Considerations](https://learn.microsoft.com/en-us/azure/bot-service/bot-builder-authentication?view=azure-bot-service-4.0)[: Ensure that the client-side implementation adheres to security best practices, such as using HTTPS, validating tokens, and handling token expiration gracefully](https://learn.microsoft.com/en-us/azure/bot-service/bot-builder-authentication?view=azure-bot-service-4.0)[2](https://learn.microsoft.com/en-us/azure/bot-service/bot-builder-authentication?view=azure-bot-service-4.0).
- Configure Web Chat: Ensure that the Web Chat control is configured to support authentication and can handle token exchange requests.
- Intercept OAuth Cards: Implement logic to intercept OAuth cards and handle token exchange requests.
- Send Custom Data: Ensure that custom data is included in the activity payload when initiating a conversation with the bot.
-
navba-MSFT 24,890 Reputation points • Microsoft Employee
2024-07-22T08:06:05.2566667+00:00 @REDDY, REDDYVALLA NAVEENKUMAR To answer your second question about the Identity Service providers, the supported lists are provided here:
Sign in to comment