Technical overview

The following illustration shows how a user is signed in without seeing a login prompt (SSO) in Copilot Studio:

  1. The copilot user enters a phrase that triggers a sign-in topic. The sign-in topic is designed to sign the user in and use the user's authenticated token (AuthToken variable).

  2. Copilot Studio sends a login prompt to allow the user to sign in with their configured identity provider.

  3. The copilot's custom canvas intercepts the sign-in prompt and requests an on-behalf-of (OBO) token from Microsoft Entra ID. The canvas sends the token to the copilot.

  4. On receipt of the OBO token, the copilot exchanges the OBO token for an "access token" and fills in the AuthToken variable using the access token's value. The IsLoggedIn variable is also set at this time.

Create an app registration in Microsoft Entra ID for your custom canvas

To enable SSO, you need two separate app registrations:

Important

You can't reuse the same app registration for both your copilot's user authentication and your custom canvas.

Create an app registration for the copilot's canvas

  1. Sign in to the Azure portal.

  2. Go to App registrations, either by selecting the icon or searching in the top search bar.

  3. Select New registration.

  4. Enter a name for the registration. It can be helpful to use the name of the copilot whose canvas you're registering and include "canvas" to help separate it from the app registration for authentication.

    For example, if your copilot is called "Contoso sales help," you might name the app registration as "ContosoSalesCanvas" or something similar.

  5. Select the account type under Supported account types. We recommend you select Accounts in any organizational directory (Any Microsoft Entra ID directory - Multitenant) and personal Microsoft accounts (for example Skype, Xbox).

  6. Leave the Redirect URI section blank for now, as you enter that information in the next steps. Select Register.

  7. After the registration is completed, it opens to the Overview page. Go to Manifest. Confirm that accessTokenAcceptedVersion is set to 2. If it isn't, change it to 2 and then select Save.

Add the redirect URL

  1. With the registration open, go to Authentication and then select Add a platform.

  2. On the configure platforms blade, select Web.

  3. Under Redirect URIs, add the full URL to the page where your chat canvas is hosted. Under the Implicit grant section, select the Id Tokens and Access Tokens checkboxes.

  4. Select Configure to confirm your changes.

  5. Go to API Permissions. Select Grant admin consent for <your tenant name> and then Yes.

    Important

    To avoid users from having to consent to each application, a Global Administrator, Application Administrator, or a Cloud Application Administrator must grant tenant-wide consent to your app registrations.

Define a custom scope for your copilot

Define a custom scope by exposing an API for the canvas app registration within the authentication app registration. Scopes allow you to determine user and admin roles and access rights.

This step creates a trust relationship between the authentication app registration for authentication and the app registration for your custom canvas.

  1. Open the app registration that you created when you configured authentication.

  2. Go to API Permissions and ensure that the correct permissions are added for your copilot. Select Grant admin consent for <your tenant name> and then Yes.

    Important

    To avoid users from having to consent to each application, a Global Administrator, Application Administrator, or a Cloud Application Administrator must grant tenant-wide consent to your app registrations.

  3. Go to Expose an API and select Add a scope.

  4. Enter a name for the scope, along with the display information that should be shown to users when they come to the SSO screen. Select Add scope.

  5. Select Add a client application.

  6. Enter the Application (client) ID from the Overview page for the canvas app registration into the Client ID field. Select the checkbox for the listed scope that you created.

  7. Select Add application.

Configure authentication in Copilot Studio to enable SSO

The Token Exchange URL in the Copilot Studio authentication configuration page is used to exchange the OBO token for the requested access token through the bot framework.

Copilot Studio calls into Microsoft Entra ID to perform the actual exchange.

  1. Sign in to Copilot Studio.

  2. Confirm you've selected the copilot you want to enable authentication for by selecting the copilot icon on the top menu and choosing the correct copilot.

  3. In the navigation menu, under Settings, select Security. Then select the Authentication card.

  4. Enter the full scope URI from the Expose an API blade for the copilot's authentication app registration in the Token exchange URL field. The URI is in the format of api://1234-4567/scope.name.

  5. Select Save and then publish the copilot content.

Configure your custom canvas HTML code to enable SSO

Update the custom canvas page where the copilot is located to intercept the login card request and exchange the OBO token.

  1. Configure the Microsoft Authentication Library (MSAL) by adding the following code into a <script> tag in your <head> section.

  2. Update clientId with the Application (client) ID for the canvas app registration. Replace <Directory ID> with the Directory (tenant) ID. You get these IDs from the Overview page for the canvas app registration.

    HTML
    <head>
     <script>
       var clientApplication;
         (function () {
           var msalConfig = {
               auth: {
                 clientId: '<Client ID [CanvasClientId]>',
                 authority: 'https://login.microsoftonline.com/<Directory ID>'
               },
               cache: {
                 cacheLocation: 'localStorage',
                 storeAuthStateInCookie: false
               }
           };
           if (!clientApplication) {
             clientApplication = new Msal.UserAgentApplication(msalConfig);
           }
         } ());
     </script>
    </head>
    
  3. Insert the following <script> in the <body> section. This script calls a method to retrieve the resourceUrl and exchange your current token for a token requested by the OAuth prompt.

    HTML
    <script>
    function getOAuthCardResourceUri(activity) {
      if (activity &&
           activity.attachments &&
           activity.attachments[0] &&
           activity.attachments[0].contentType === 'application/vnd.microsoft.card.oauth' &&
           activity.attachments[0].content.tokenExchangeResource) {
             // asking for token exchange with Microsoft Entra ID
             return activity.attachments[0].content.tokenExchangeResource.uri;
       }
    }
    
    function exchangeTokenAsync(resourceUri) {
      let user = clientApplication.getAccount();
       if (user) {
         let requestObj = {
           scopes: [resourceUri]
         };
         return clientApplication.acquireTokenSilent(requestObj)
           .then(function (tokenResponse) {
             return tokenResponse.accessToken;
             })
             .catch(function (error) {
               console.log(error);
             });
             }
             else {
             return Promise.resolve(null);
       }
    }
    </script>
    
  4. Insert the following <script> in the <body> section. Within the main method, this code adds a conditional to your store, with your copilot's unique identifier. It also generates a unique ID as your userId variable.

  5. Update <COPILOT ID> with your copilot's ID. You can see your copilot's ID by going to the Channels tab for the copilot you're using, and selecting Mobile app on the Copilot Studio portal.


    HTML
    <script>
        (async function main() {
    
            // Add your COPILOT ID below 
            var BOT_ID = "<BOT ID>";
            var theURL = "https://powerva.microsoft.com/api/botmanagement/v1/directline/directlinetoken?botId=" + BOT_ID;
    
            const {
                token
            } = await fetchJSON(theURL);
    
            var directline = await fetchJSON(regionalChannelSettingsURL).then(res=> res.channelUrlsById.directline); 
    
            const directLine = window.WebChat.createDirectLine({
                domain: `${directline}v3/directline`,
                token
            });
    
            var userID = clientApplication.account?.accountIdentifier != null ?
                ("Your-customized-prefix-max-20-characters" + clientApplication.account.accountIdentifier).substr(0, 64) :
                (Math.random().toString() + Date.now().toString()).substr(0, 64); // Make sure this will not exceed 64 characters 
            const store = WebChat.createStore({}, ({
                dispatch
            }) => next => action => {
                const {
                    type
                } = action;
                if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
                    dispatch({
                        type: 'WEB_CHAT/SEND_EVENT',
                        payload: {
                            name: 'startConversation',
                            type: 'event',
                            value: {
                                text: "hello"
                            }
                        }
                    });
                    return next(action);
                }
                if (action.type === 'DIRECT_LINE/INCOMING_ACTIVITY') {
                    const activity = action.payload.activity;
                    let resourceUri;
                    if (activity.from && activity.from.role === 'bot' &&
                        (resourceUri = getOAuthCardResourceUri(activity))) {
                        exchangeTokenAsync(resourceUri).then(function(token) {
                            if (token) {
                                directLine.postActivity({
                                    type: 'invoke',
                                    name: 'signin/tokenExchange',
                                    value: {
                                        id: activity.attachments[0].content.tokenExchangeResource.id,
                                        connectionName: activity.attachments[0].content.connectionName,
                                        token,
                                    },
                                    "from": {
                                        id: userID,
                                        name: clientApplication.account.name,
                                        role: "user"
                                    }
                                }).subscribe(
                                    id => {
                                        if (id === 'retry') {
                                            // copilot was not able to handle the invoke, so display the oauthCard
                                            return next(action);
                                        }
                                        // else: tokenexchange successful and we do not display the oauthCard
                                    },
                                    error => {
                                        // an error occurred to display the oauthCard
                                        return next(action);
                                    }
                                );
                                return;
                            } else
                                return next(action);
                        });
                    } else
                        return next(action);
                } else
                    return next(action);
            });
    
            const styleOptions = {
    
                // Add styleOptions to customize Web Chat canvas
                hideUploadButton: true
            };
    
            window.WebChat.renderWebChat({
                    directLine: directLine,
                    store,
                    userID: userID,
                    styleOptions
                },
                document.getElementById('webchat')
            );
        })().catch(err => console.error("An error occurred: " + err));
    </script>
    

Full sample code

For more information, you can find the full sample code, with the MSAL and store conditional scripts already included at our GitHub repo.