cancel
Showing results for 
Search instead for 
Did you mean: 
Reply
Anonymous
Not applicable

How to configure SSO on a intranet page (SharePoint)

Hi,

 

I have been trying to configure SSO on our organization SharePoint website using PVA. But I don't see it to be working. I have been referring to the below URLs:

 

SSO doc 

https://docs.microsoft.com/en-us/power-virtual-agents/configure-sso#:~:text=Power%20Virtual%20Agents....

 

GitHub Sample code doc

https://github.com/microsoft/PowerVirtualAgentsSamples/blob/master/BuildYourOwnCanvasSamples/3.singl...


I have created a HTML file adding the SSO code provided from the above doc and published in the SharePoint website. I do not wish to see the login sign in card which asks to pass the token rather I need to Sign-in directly once I click the Chatbot button.

 

pva1.png

 

I have also posted regarding the same in the past as well. But no luck. Any help is much appreciated. 

 

Regards,

Hemanth

1 ACCEPTED SOLUTION

Accepted Solutions
Anonymous
Not applicable

Hi @Anonymous 

 

Not sure if you are still facing issue with SSO working. I have got this issue fixed on my end and would like to share some inputs on that

 

1) I have seen the behavior of SSO and login that shows up in PVA bot is not consistent among browsers. Also you may be aware that the login status is stored in local stroage/session as specified in the MSAL.

 

2) I also saw that the code in github had issues related to how userId is passed. The particular line that was causing this login to come was this one below:

 

var userID = clientApplication.account!=null && clientApplication.account.accountIdentifier != null ?
("<Prefix>" + clientApplication.account.accountIdentifier).substr(0, 64) :
(Math.random().toString() + Date.now().toString()).substr(0, 64); // Make sure this will not exceed 64 characters

 

The userID is being used in the webchat to pass the UserID and this is supposed to be the User Id from AAD which is not the case with the <Prefix>. I fixed this to pass just the Id and no prefix.

 

var userID = clientApplication.account!=null && clientApplication.account.accountIdentifier != null ?
clientApplication.account.accountIdentifier:
(Math.random().toString() + Date.now().toString()).substr(0, 64); // Make sure this will not exceed 64 characters

 

This should take care of passing right UserID

 

if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED')
{
/*
dispatch({
type: 'WEB_CHAT/SEND_EVENT',
payload: {
name: 'startConversation',
type: 'event',
value: {
text: "Hello"
}
}
});
return next(action);
*/
}

 

This is the code that is causing the Login to appear always. One more fix which I did in my case is to force the user login to happen before the webchat is displayed. This will make sure that the user token is created when webchat is initialized and what I have noticed is that after the below MSAL js changes, I never see a Login box in the chat.

 

if (!clientApplication)
{
clientApplication = new Msal.UserAgentApplication(msalConfig);
clientApplication.handleRedirectCallback(authRedirectCallBack);

//Below code will silently try to get token without popup. If there is no login already exists it will throw exception.
//As 2nd step, Login will be forced using LoginRedirect method
var newRequest =
{
scopes: ["user.read", 'openid', 'profile'],
}

clientApplication.acquireTokenSilent(newRequest).then(function(response)
{
//Now get the user display name
let user = clientApplication.getAccount();
document.getElementById("divUser").style.display="block";
document.getElementById("userName").innerHTML = " " + user.name;
}
).catch(function (error)
{
document.getElementById("divUser").style.display="block";
//Now get the user display name
document.getElementById("userName").innerHTML = "Not Logged in";
$('#divPopup').modal({backdrop: 'static',keyboard: false});
setTimeout(function()
{
//Now redirect to URI so that token will be created
clientApplication.loginRedirect(newRequest);

}, 2000);
});
}

 

The above code is trying to get token silently and if that fails it just forces login using redirect. This will make sure that first time user logs in, it will force token to be created and then it will be stored in local storage.

 

After this fix, my bot works fine all the time in the external web page. Hope this helps. Do not hesitate to ask any further questions.

View solution in original post

26 REPLIES 26
Anonymous
Not applicable

Hi @Anonymous 

 

Not sure if you are still facing issue with SSO working. I have got this issue fixed on my end and would like to share some inputs on that

 

1) I have seen the behavior of SSO and login that shows up in PVA bot is not consistent among browsers. Also you may be aware that the login status is stored in local stroage/session as specified in the MSAL.

 

2) I also saw that the code in github had issues related to how userId is passed. The particular line that was causing this login to come was this one below:

 

var userID = clientApplication.account!=null && clientApplication.account.accountIdentifier != null ?
("<Prefix>" + clientApplication.account.accountIdentifier).substr(0, 64) :
(Math.random().toString() + Date.now().toString()).substr(0, 64); // Make sure this will not exceed 64 characters

 

The userID is being used in the webchat to pass the UserID and this is supposed to be the User Id from AAD which is not the case with the <Prefix>. I fixed this to pass just the Id and no prefix.

 

var userID = clientApplication.account!=null && clientApplication.account.accountIdentifier != null ?
clientApplication.account.accountIdentifier:
(Math.random().toString() + Date.now().toString()).substr(0, 64); // Make sure this will not exceed 64 characters

 

This should take care of passing right UserID

 

if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED')
{
/*
dispatch({
type: 'WEB_CHAT/SEND_EVENT',
payload: {
name: 'startConversation',
type: 'event',
value: {
text: "Hello"
}
}
});
return next(action);
*/
}

 

This is the code that is causing the Login to appear always. One more fix which I did in my case is to force the user login to happen before the webchat is displayed. This will make sure that the user token is created when webchat is initialized and what I have noticed is that after the below MSAL js changes, I never see a Login box in the chat.

 

if (!clientApplication)
{
clientApplication = new Msal.UserAgentApplication(msalConfig);
clientApplication.handleRedirectCallback(authRedirectCallBack);

//Below code will silently try to get token without popup. If there is no login already exists it will throw exception.
//As 2nd step, Login will be forced using LoginRedirect method
var newRequest =
{
scopes: ["user.read", 'openid', 'profile'],
}

clientApplication.acquireTokenSilent(newRequest).then(function(response)
{
//Now get the user display name
let user = clientApplication.getAccount();
document.getElementById("divUser").style.display="block";
document.getElementById("userName").innerHTML = " " + user.name;
}
).catch(function (error)
{
document.getElementById("divUser").style.display="block";
//Now get the user display name
document.getElementById("userName").innerHTML = "Not Logged in";
$('#divPopup').modal({backdrop: 'static',keyboard: false});
setTimeout(function()
{
//Now redirect to URI so that token will be created
clientApplication.loginRedirect(newRequest);

}, 2000);
});
}

 

The above code is trying to get token silently and if that fails it just forces login using redirect. This will make sure that first time user logs in, it will force token to be created and then it will be stored in local storage.

 

After this fix, my bot works fine all the time in the external web page. Hope this helps. Do not hesitate to ask any further questions.

Anonymous
Not applicable

Hi @Anonymous 

 

Thanks a lot for responding back..

 

Yes, I still face issues with SSO. Below is the code that I am using to achieve SSO. I have added the changes that was told by you to my code. I do not want to use the login button since I have already logged into my SharePoint website.

 

<!DOCTYPE html>
<html>
  <head>
    <title>Virtual Agent</title>
    <script src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>

    <script
      type="text/javascript"
      src="https://alcdn.msauth.net/lib/1.2.0/js/msal.js"></script>

    <script
      src="https://unpkg.com/@azure/storage-blob@10.3.0/browser/azure-storage.blob.min.js"
      integrity="sha384-fsfhtLyVQo3L3Bh73qgQoRR328xEeXnRGdoi53kjo1uectCfAHFfavrBBN2Nkbdf"
      crossorigin="anonymous"></script>

    <script type="text/javascript">
      if (typeof Msal === "undefined")
        document.write(
          unescape(
            "%3Cscript src='https://alcdn.msftauth.net/lib/1.2.0/js/msal.js' type='text/javascript' %3E%3C/script%3E"
          )
        );
    </script>

    <style>
      html,
      body {
        height: 100%;
      }

      body {
        margin: 0;
      }

      .modal {
        display: none; /* Hidden by default */
        position: fixed; /* Stay in place */
        z-index: 1; /* Sit on top */
        padding-top: 100px; /* Location of the box */
        left: 0;
        top: 0;
        width: 100%; /* Full width */
        height: 100%; /* Full height */
        overflow: auto; /* Enable scroll if needed */
        background-color: rgb(0, 0, 0); /* Fallback color */
        background-color: rgba(0, 0, 0, 0.4); /* Black w/ opacity */
      }

      .modal-content {
        background-color: #fefefe;
        margin: auto;
        padding: 10px;
        border: 1px solid #888;
        width: 500px;
        height: 575px;
      }
      .close {
        color: black;
        float: right;
        font-size: 28px;
        font-weight: bold;
      }

      .close:hover,
      .close:focus {
        color: #000;
        text-decoration: none;
        cursor: pointer;
      }

      .main {
        margin: 18px;
        border-radius: 4px;
      }

      div[role="form"] {
        background-color: #3392ff;
      }

      #webchat {
        position: center;
        height: 530px;
        width: 100%;
        top: 60px;
        overflow: hidden;
      }
      #heading {
        padding-bottom: 5px;
      }

      h1 {
        font-size: 14px;
        font-family: Segoe UI;
        font-style: normal;
        font-weight: 600;
        font-size: 14px;
        line-height: 20px;
        color: #f3f2f1;
        letter-spacing: 0.005em;
        display: table-cell;
        vertical-align: middle;
        padding: 13px 0px 0px 20px;
      }

      #login {
        position: fixed;
        margin-left: 150px;
      }

      .span {
        font-weight: bold;
      }
      #myBtn {
        position: fixed;
        float: right;
        outline: none;
        width: 60px;
        height: 80px;
        margin: auto auto auto 10px;
      }
      button:hover {
        background-color: transparent;
      }
    </style>
  </head>
  <body>

    <button id="myBtn" type="button">Power Virtual Agent</button>

    <button id="login" name="login" onclick="onSignInClick()" style="background-color: aliceblue">Log In</button>

    <div id="myModal" class="modal">

      <div class="modal-content" style="background-color: #ffd933">

        <span class="close">&times;</span>
        <div id="chatwindow">
          <div id="heading">
            <span class="span"><strong>Virtual Agent</strong></span>
            <label id="divUser" name="divUser" style="width: 75%; height: 15px; border-color: Transparent"></label>
            <label id="userName" name="userName" style="width: 75%; height: 15px; border-color: Transparent">Not logged in.</label>
          </div>
          <div id="webchat"></div>
        </div>
      </div>
    </div>

    <script>

      var modal = document.getElementById("myModal");
      var btn = document.getElementById("myBtn");
      var span = document.getElementsByClassName("close")[0];
      btn.onclick = function () {
        modal.style.display = "block";
      };
      span.onclick = function () {
        modal.style.display = "none";
      };
      window.onclick = function (event) {
        if (event.target == modal) {
          modal.style.display = "none";
        }
      };

    </script>

    <script>
      function onSignin(idToken) {
        let user = clientApplication.getAccount();
        alert("User: " + JSON.stringify(user));

        document.getElementById("userName").innerHTML = "Currently logged in as " + user.name;
        let requestObj1 = {
          scopes: ["user.read", "openid", "profile"],
        };
      }

      function onSignInClick() {
        let user = clientApplication.getAccount();
        let requestObj = {
          scopes: ["user.read", "openid", "profile"],
        };

        clientApplication.loginPopup(requestObj).then(onSignin).catch(function (error) {
            console.log("error: " + error);
          });
      }

      function getOAuthCardResourceUri(activity) {
        if (
          activity &&
          activity.attachments &&
          activity.attachments[0] &&
          activity.attachments[0].contentType === "application/vnd.microsoft.card.oauth" &&
          activity.attachments[0].content.tokenExchangeResource)
          {
          return activity.attachments[0].content.tokenExchangeResource.uri;
          }
      }

      function exchangeTokenAsync(resourceUri) {
        let user = clientApplication.getAccount();

        if (user) {
          console.log("User exist " + JSON.stringify(user));

          let requestObj = {
            scopes: [resourceUri],
          };
          console.log("RequestObj: " + JSON.stringify(requestObj));

          return clientApplication.acquireTokenSilent(requestObj).then(function (tokenResponse) {
              console.log("ExchangeTokenAsync requestObj: " + tokenResponse.accessToken);
              return tokenResponse.accessToken;
            })
            .catch(function (error) {
              console.log("ExchangeTokenAsync error: " + error);
            });
        } else {
          return Promise.resolve(null);
        }
      }

      async function fetchJSON(url, options = {}) {
        const res = await fetch(url, {
          ...options,
          headers: {
            ...options.headers,
            accept: "application/json",
          },
        });

        if (!res.ok) {
          throw new Error(`Failed to fetch JSON due to ${res.status}`);
        }

        return await res.json();
      }
    </script>

    <script>
      var clientApplication;

      (function () {
        var msalConfig = {
          auth: {
            clientId: "<Removed Canvas Client ID>",
            authority:"https://login.microsoftonline.com/<Removed Directory ID>",
          },
          cache: {
            cacheLocation: "localStorage",
            storeAuthStateInCookie: false,
          },
        };
        if (!clientApplication) {
          clientApplication = new Msal.UserAgentApplication(msalConfig);

          // I get an error stating "Uncaught ReferenceError: authRedirectCallBack is not defined"
          clientApplication.handleRedirectCallback(authRedirectCallBack);

          //Below code will silently try to get token without popup. If there is no login already exists it will throw exception.
          //As 2nd step, Login will be forced using LoginRedirect method
          var newRequest = {
            scopes: ["user.read", "openid", "profile"],
          };

          clientApplication.acquireTokenSilent(newRequest).then(function (response)
          {
              //Now get the user display name
              let user = clientApplication.getAccount();
              document.getElementById("divUser").style.display = "block";
              document.getElementById("userName").innerHTML = " " + user.name;
          })
          .catch(function (error)
          {
              document.getElementById("divUser").style.display = "block";
              //Now get the user display name
              document.getElementById("userName").innerHTML = "Not Logged in";
              $("#divPopup").modal({ backdrop: "static", keyboard: false });
              setTimeout(function ()
              {
                //Now redirect to URI so that token will be created
                clientApplication.loginRedirect(newRequest);
              }, 2000);
          });
        }
      })();

      (async function main() {

        var BOT_ID = "<Removed BOT ID>";
        var theURL = "https://powerva.microsoft.com/api/botmanagement/v1/directline/directlinetoken?botId=" + BOT_ID;

        var userId = clientApplication.account!=null && clientApplication.account.accountIdentifier != null ? clientApplication.account.accountIdentifier: (Math.random().toString() + Date.now().toString()).substr(0, 64); // Make sure this will not exceed 64 characters

        console.log("Async function main userId: " + userId);

        const { token } = await fetchJSON(theURL);
        const directLine = window.WebChat.createDirectLine({ token });
        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) => {

                          console.log("id: " + id);

                          if (id === "retry")
                          {
                            console.log(`Bot was not able to handle the invoke, so display the oauthCard`);
                            return next(action);
                          }
                          console.log(`Else: tokenexchange successful and we do not display the oauthCard`);
                        },
                        (error) => {
                          console.log(`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>
  </body>
</html>

 

I am getting an error stating

"Uncaught ReferenceError: authRedirectCallBack is not defined"  from the below line of code.
clientApplication.handleRedirectCallback(authRedirectCallBack);

 

So I just created a function

 

function authRedirectCallBack(error, response) {
if (error) {
console.log(error);
}
}
 
And I saw my name to be displayed on the label tag on the bot screen as below.
a1.jpg
 

I also see the below error as well

webchat.js:2 POST https://directline.botframework.com/v3/directline/conversations/6EES0CsPuThCYcqw3AK1Cb-6/activities 502

 

It always entry into the id === "retry" block of code.

 

if (id === "retry")
{
console.log(`Bot was not able to handle the invoke, so display the oauthCard`);
return next(action);
}

 

I still get the login box when I start to chat with my bot. 

 

Can you please help me solve this. Thanks.

Anonymous
Not applicable

@Anonymous ,

 

With this approach, the redirect URL needs to be passed

 

var msalConfig = 
	{
		auth: 
		{
	    	clientId: '', //Client Id of the AAD Aopp
	   		authority: 'https://login.microsoftonline.com/<TenantId>', //Login
	    	redirectUri: "<SharePoint Page where Bot will be hosted>", //URL that MSAL will redirect to when token is created
	    	navigateToLoginRequestUrl: false //Flag whether to navigate to page if token is not found
		},
	   	cache: 
	   	{
	     cacheLocation: 'localStorage', //Where to store the token information - Local storage
	     storeAuthStateInCookie: false //Whether to store auth information in cookie
	   	}
	};


if (!clientApplication) 
{
		clientApplication = new Msal.UserAgentApplication(msalConfig);
		clientApplication.handleRedirectCallback(authRedirectCallBack);	
}

function authRedirectCallBack(error, response) 
{
    //Do Nothing Here since we don't come back to this page.
    
}

Also make sure to add the redirect url of the SharePoint page where the bot is hosted in AAD App redirect Uri otherwise you will receive a error. 

 

Also can you check your AAD App settings to make sure the configuration is correct. Make sure to add your redirect uri.

 

Hope this helps.

Anonymous
Not applicable

@Anonymous 

 

Thank you, I have done the code changes as above. But no luck. I still see the login card.


Below is the code section of MSAL and the main method.

<script>
      var clientApplication;

      (function () {
        var msalConfig =
	       {
		     auth:
		          {
	    	         clientId: '<Have removed the Client ID>', //Client Id of the AAD Aopp
	   		         authority: 'https://login.microsoftonline.com/<Have removed the Directory ID>', //Login
	    	         redirectUri: "https://<org name>.sharepoint.com/sites/testing/MT/project/SitePages/Home.aspx", //URL that MSAL will redirect to when token is created
	    	         navigateToLoginRequestUrl: false //Flag whether to navigate to page if token is not found
		          },
	   	  cache:
	   	        {
	               cacheLocation: 'localStorage', //Where to store the token information - Local storage
	               storeAuthStateInCookie: false //Whether to store auth information in cookie
	   	        }
	       };

             if (!clientApplication)
             {
		             clientApplication = new Msal.UserAgentApplication(msalConfig);
		             clientApplication.handleRedirectCallback(authRedirectCallBack);
             }

      function authRedirectCallBack(error, response)
      {
        //Do Nothing Here since we don't come back to this page.

      }


          //Below code will silently try to get token without popup. If there is no login already exists it will throw exception.
          //As 2nd step, Login will be forced using LoginRedirect method
          var newRequest = {
            scopes: ["user.read", "openid", "profile"],
          };

          clientApplication.acquireTokenSilent(newRequest).then(function (response)
          {
              //Now get the user display name
              let user = clientApplication.getAccount();
              document.getElementById("divUser").style.display = "block";
              document.getElementById("userName").innerHTML = " " + user.name;
          })
          .catch(function (error)
          {
              document.getElementById("divUser").style.display = "block";
              //Now get the user display name
              document.getElementById("userName").innerHTML = "Not Logged in";
              $("#divPopup").modal({ backdrop: "static", keyboard: false });
              setTimeout(function ()
              {
                //Now redirect to URI so that token will be created
                clientApplication.loginRedirect(newRequest);
              }, 2000);
          });
      })();

      (async function main() {

        var BOT_ID = "<Have removed the Bot ID>";
        var theURL = "https://powerva.microsoft.com/api/botmanagement/v1/directline/directlinetoken?botId=" + BOT_ID;

        var userId = clientApplication.account!=null && clientApplication.account.accountIdentifier != null ? clientApplication.account.accountIdentifier: (Math.random().toString() + Date.now().toString()).substr(0, 64); // Make sure this will not exceed 64 characters

        console.log("Async function main userId: " + userId);

        const { token } = await fetchJSON(theURL);
        const directLine = window.WebChat.createDirectLine({ token });
        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) => {

                          console.log("id: " + id);

                          if (id === "retry")
                          {
                            console.log(`Bot was not able to handle the invoke, so display the oauthCard`);
                            return next(action);
                          }
                          console.log(`Else: tokenexchange successful and we do not display the oauthCard`);
                        },
                        (error) => {
                          console.log(`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>

 

Below is code section of all functions

  <script>
      function onSignin(idToken) {
        let user = clientApplication.getAccount();
        alert("User: " + JSON.stringify(user));

        document.getElementById("userName").innerHTML = "Currently logged in as " + user.name;
        let requestObj1 = {
          scopes: ["user.read", "openid", "profile"],
        };
      }

      function onSignInClick() {
        let user = clientApplication.getAccount();
        let requestObj = {
          scopes: ["user.read", "openid", "profile"],
        };

        clientApplication.loginPopup(requestObj).then(onSignin).catch(function (error) {
            console.log("error: " + error);
          });
      }

      function getOAuthCardResourceUri(activity) {
        if (
          activity &&
          activity.attachments &&
          activity.attachments[0] &&
          activity.attachments[0].contentType === "application/vnd.microsoft.card.oauth" &&
          activity.attachments[0].content.tokenExchangeResource)
          {
          return activity.attachments[0].content.tokenExchangeResource.uri;
          }
      }

      function exchangeTokenAsync(resourceUri) {
        let user = clientApplication.getAccount();

        if (user) {
          console.log("User exist " + JSON.stringify(user));

          let requestObj = {
            scopes: [resourceUri],
          };
          console.log("RequestObj: " + JSON.stringify(requestObj));

          return clientApplication.acquireTokenSilent(requestObj).then(function (tokenResponse) {
              console.log("ExchangeTokenAsync requestObj: " + tokenResponse.accessToken);
              return tokenResponse.accessToken;
            })
            .catch(function (error) {
              console.log("ExchangeTokenAsync error: " + error);
            });
        } else {
          return Promise.resolve(null);
        }
      }

      async function fetchJSON(url, options = {}) {
        const res = await fetch(url, {
          ...options,
          headers: {
            ...options.headers,
            accept: "application/json",
          },
        });

        if (!res.ok) {
          throw new Error(`Failed to fetch JSON due to ${res.status}`);
        }

        return await res.json();
      }
    </script>


I have added the SharePoint redirect uri in the code and on the AAD app as well.

The SSO configuration in Azure AD are done as per the doc provided by Microsoft.

 

Azure Canvas/SSO App registration

azure2.jpg

 

Azure Authentication App registration

azure3.jpg

 

In the console I see the below error

 

POST https://directline.botframework.com/v3/directline/conversations/52jH6J9MMCFFFk77eFTDHO-f/activities 502

 

And as the id is "retry" it enters into the if block of (id==='retry') so the login card always shows up.

Anonymous
Not applicable

I rally have not seen this error. This certainly means the bot is not able to communicate may be due to token exchange issue. Can you verify your bot token exchange url and make sure it is update in AAD app as well as PVA settings? Also the error 502 means some kind of user error. Can you try to step through the code and put a breakpoint to see what part f the code is failing. As the user tries to talk to bot, the request and response changes. Check that out

Anonymous
Not applicable

@Anonymous 

I did try to add break points and try to check which step is failing, But I am not able to figure which step fails from the code, as per the below snapshot I could see my name being passed but the end I still see the login card on by chatbot.

 

code.jpg

 

Both the redirect uri on the AAD app registration and on code are same. I have done all the code changes as updated by you. Not sure what is causing this issue. 

Anonymous
Not applicable

@Anonymous  The reason why you are seeing your user name is due to MSAL authenticating. I think the issue is with exchangeTokenAsync(). Can you debug into this and see what is happening after receiving the token. Did you check your token exchange Url to match with AAD app? 

Anonymous
Not applicable

@Anonymous 

 

The token exchange Uri that I have added in the PVA Authentication section and the AAD Canvas app both matches.

Please find the below snapshot of exchangeTokenAsync() function code with breakpoint

 

code2.jpg

Below error is what i see on my console as well.

code1.jpg

Anonymous
Not applicable

Hi @Anonymous 

 

I was successfully able to achieve SSO. I did the changes on the PVA Authentication section by changing the Service Provider from Generic OAuth 2 to Azure Active Directory V2 which was the main reason for the POST error that I was getting in the console. By doing this and the code changes that you have provided me help me a lot to successfully achieve SSO. Many Thanks.

Helpful resources

Announcements

It's #MPPC23 Week! Check Out the Community Sessions and Events Happening in Vegas

After all the planning and preparing, the annual Microsoft Power Platform Conference is finally here! We are excited to see so many of our community in Las Vegas this week. To help make sure you don't miss any of the workshops, sessions, and events we have planned, make sure to check out this handy Community One-Sheet, and download the pdf today! Make sure to stop by the Community Lounge to meet @hugobernier, @EricArcher, @heaher_italent, and @AshleyFelts from our team! See you in Vegas!      

Join Us for the First-Ever Biz Apps Community User Group Meeting: Live from MPPC23

      Join us for the first-ever the Biz Apps Community User Group meeting live from the Power Platform Conference! This one hour user group meeting is all about discovering the value and benefits of User Groups! Discover how you can find a group in your local area or about specific topics where you can learn new skills and meet like-minded people as a user group member.   Hear from User Group leaders about why they do what they do and what resources they receive to help them succeed as community ambassadors. If you have never attended a User Group meeting before, this will be a great introduction! We hope you are inspired to find a group that meets your unique interests!   October 5th at 2:15 pm Pacific time   If you're attending #MPPC23 in Las Vegas, join us in person! Find out more here: https://powerplatformconf.com/#!/session/Biz%20Apps%20Community%20User%20Group%20Meeting%20-%20Live%20from%20MPPC/6172   Not at MPPC23? Attend vvirtually by registering here: https://aka.ms/MPPCusergroupmeeting2023    If you can't attend this meeting live, don't worry! We will record this meeting and share it with the Community at powerusers.microsoft.com 

Back to Basics: Tuesday Tip #1: All About YOUR Community Account

We are excited to kick off our new #TuesdayTIps series, "Back to Basics." This weekly series is our way of helping the amazing members of our community--both new members and seasoned veterans--learn and grow in how to best engage in the community! Each Tuesday, we will feature new areas of content that will help you best understand the community--from ranking and badges to profile avatars, from Super Users to blogging in the community. Our hope is that this information will help each of our community members grow in their experience with Power Platform, with the community, and with each other!     This Week's Tips: Account Support: Changing Passwords, Changing Email Addresses or Usernames, "Need Admin Approval," Etc.Wondering how to get support for your community account? Check out the details on these common questions and more. Just follow the link below for articles that explain it all.Community Account Support - Power Platform Community (microsoft.com)   All About GDPR: How It Affects Closing Your Community Account (And Why You Should Think Twice Before You Do)GDPR, the General Data Protection Regulation (GDPR), took effect May 25th 2018. A European privacy law, GDPR imposes new rules on companies and other organizations offering goods and services to people in the European Union (EU), or that collect and analyze data tied to EU residents. GDPR applies no matter where you are located, and it affects what happens when you decide to close your account. Read the details here:All About GDPR - Power Platform Community (microsoft.com)   Getting to Know You: Setting Up Your Community Profile, Customizing Your Profile, and More.Your community profile helps other members of the community get to know you as you begin to engage and interact. Your profile is a mirror of your activity in the community. Find out how to set it up, change your avatar, adjust your time zone, and more. Click on the link below to find out how:Community Profile, Time Zone, Picture (Avatar) & D... - Power Platform Community (microsoft.com)   That's it for this week. Tune in for more Tuesday Tips next Tuesday and join the community as we get "Back to Basics."

Announcing the MPPC's Got Power Talent Show at #MPPC23

Are you attending the Microsoft Power Platform Conference 2023 in Las Vegas? If so, we invite you to join us for the MPPC's Got Power Talent Show!      Our talent show is more than a show—it's a grand celebration of connection, inspiration, and shared journeys. Through stories, skills, and collective experiences, we come together to uplift, inspire, and revel in the magic of our community's diverse talents. This year, our talent event promises to be an unforgettable experience, echoing louder and brighter than anything you've seen before.    We're casting a wider net with three captivating categories:  Demo Technical Solutions: Show us your Power Platform innovations, be it apps, flows, chatbots, websites or dashboards... Storytelling: Share tales of your journey with Power Platform. Hidden Talents: Unveil your creative side—be it dancing, singing, rapping, poetry, or comedy. Let your talent shine!    Got That Special Spark? A Story That Demands to Be Heard? Your moment is now!  Sign up to Showcase Your Brilliance: https://aka.ms/MPPCGotPowerSignUp  Deadline for submissions: Thursday, Sept 28th    How It Works:  Submit this form to sign up: https://aka.ms/MPPCGotPowerSignUp  We'll contact you if you're selected. Get ready to be onstage!  The Spotlight is Yours: Each participant has 3-5 minutes to shine, with insightful commentary from our panel of judges. We’re not just giving you a stage; we’re handing you the platform to make your mark.     Be the Story We Tell: Your talents and narratives will not just entertain but inspire, serving as the bedrock for our community’s future stories and successes.    Celebration, Surprises, and Connections: As the curtain falls, the excitement continues! Await surprise awards and seize the chance to mingle with industry experts, Microsoft Power Platform leaders, and community luminaries. It's not just a show; it's an opportunity to forge connections and celebrate shared successes.    Event Details:  Date and Time: Wed Oct 4th, 6:30-9:00PM   Location: MPPC23 at the MGM Grand, Las Vegas, NV, USA  

A Celebration of What We've Achieved--And Announcing Our Winners

As the sun sets on the #SummerofSolutions Challenge, it's time to reflect and celebrate! The journey we embarked upon together was not just about providing answers – it was about fostering a sense of community, encouraging collaboration, and unlocking the true potential of the Power Platform tools.   From the initial announcement to the final week's push, the Summer of Solutions Challenge has been a whirlwind of engagement and growth. It was a call to action for every member of our Power Platform community, urging them to contribute their expertise, engage in discussions, and elevate collective knowledge across the community as part of the low-code revolution.   Reflecting on the Impact As the challenge ends, it's essential to reflect on the impact it’s had across our Power Platform communities: Community Resilience: The challenge demonstrated the resilience of our community. Despite geographical distances and diverse backgrounds, we came together to contribute, learn, and collaborate. This resilience is the cornerstone of our collective strength.Diverse Expertise: The solutions shared during the challenge underscore the incredible expertise within our community. From intricate technical insights to creative problem-solving, our members showcased their diverse skill sets, enhancing our community's depth.Shared Learning: Solutions spurred shared learning. They provided opportunities for members to grasp new concepts, expand their horizons, and uncover the Power Platform tools' untapped potential. This learning ripple effect will continue to shape our growth. Empowerment: Solutions empowered community members. They validated their knowledge, boosted their confidence, and highlighted their contributions. Each solution shared was a step towards personal and communal empowerment. We are proud and thankful as we conclude the Summer of Solutions Challenge. The challenge showed the potential of teamwork, the benefit of knowledge-sharing, and the resilience of our Power Platform community. The solutions offered by each member are more than just answers; they are the expression of our shared commitment to innovation, growth, and progress!       Drum roll, Please... And now, without further ado, it's time to announce the winners who have risen above the rest in the Summer of Solutions Challenge!   These are the top community users and Super Users who have not only earned recognition but have become beacons of inspiration for us all.   Power Apps Community:  Community User Winner: @SpongYe Super User Winner: Pending Acceptance Power Automate Community:  Community User Winner: @trice602 Super User Winner: @Expiscornovus  Power Virtual Agents Community: Community User Winner: Pending AcceptanceSuper User: Pending Acceptance Power Pages Community: Community User Winner: @OOlashyn Super User Winner: @ChristianAbata   We are also pleased to announced two additional tickets that we are awarding to the Overall Top Solution providers in the following communities:    Power Apps: @LaurensM   Power Automate: @ManishSolanki    Thank you for making this challenge a resounding success. Your participation has reaffirmed the strength of our community and the boundless potential that lies within each of us. Let's keep the spirit of collaboration alive as we continue on this incredible journey in Power Platform together.Winners, we will see you in Vegas! Every other amazing solutions superstar, we will see you in the Community!Congratulations, everyone!

September featured user group leader

    Ayonija Shatakshi, a seasoned senior consultant at Improving, Ohio, is a passionate advocate for M365, SharePoint, Power Platform, and Azure, recognizing how they synergize to deliver top-notch solutions. Recently, we asked Ayonija to share her journey as a user group leader, shedding light on her motivations and the benefits she's reaped from her community involvement.      Ayonija embarked on her role as a user group leader in December 2022, driven by a desire to explore how the community leveraged various Power Platform components. When she couldn't find a suitable local group, she decided to create one herself!    Speaking about the impact of the community on her professional and personal growth, Ayonija says, "It's fascinating to witness how everyone navigates the world of Power Platform, dealing with license constraints and keeping up with new features. There's so much to learn from their experiences.        Her favorite aspect of being a user group leader is the opportunity to network and engage in face-to-face discussions with fellow enthusiasts, fostering deeper connections within the community. Offering advice to budding user group leaders, Ayonija emphasized the importance of communication and consistency, two pillars that sustain any successful community initiative.      When asked why she encourages others to become user group leaders, Ayonija said, "Being part of a user group is one of the best ways to connect with experienced professionals in the same field and glean knowledge from them. If there isn't a local group, consider starting one; you'll soon find like-minded individuals."      Her highlight from the past year as a user group leader was witnessing consistent growth within the group, a testament to the thriving community she has nurtured. Advocating for user group participation, Ayonija stated, "It's the fastest route to learning from the community, gaining insights, and staying updated on industry trends."   Check out her group: Cleveland Power Platform User Group

Users online (4,075)