单一登录-Javascript无法在Chatbot上运行

问题描述

我已经在Sharepoint网站上发布了我的聊天机器人,我正在使用以下代码来实现SSO,我正在使用2按钮登录和Power Virtual Agent。当我单击登录按钮SSO works时,我将直接通过身份验证,但是当我单击Power Virtual Agent button时,它要求我传递登录令牌。我只需要单击Power Virtual Agent按钮就可以自动对其进行身份验证。我想避免使用“登录”按钮,因为我已经登录到Sharepoint网站。

聊天机器人是使用Microsoft Power Virtual Agent创建的。

在SSO的主要代码下面。有关完整的代码click here。谁能帮我这个忙。

我正在使用Microsoft提供的doc中的代码

<!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>
</head>
<body>
    <button id="myBtn" type="button">Power Virtual Agent</button>
    
    <button id="login" name="login" onclick="onSignInClick()">Log In</button>
  <script>
        function onSignin(idToken) {
            debugger;
            let user = clientApplication.getAccount();
            document.getElementById("userName").innerHTML = "Currently logged in as " + user.name;
            
            let requestObj1 = {
                scopes: ["user.read",'openid','profile']
            };
        }

        function onSignInClick() {
            debugger;
            let requestObj = {
                scopes: ["user.read",'profile']
            };
            clientApplication.loginPopup(requestObj).then(onSignin).catch(function (error) { console.log(error) });
        }

        function getoAuthCardResourceUri(activity) {
            debugger;
            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 AAD
                return activity.attachments[0].content.tokenExchangeResource.uri;
            }
        }

        function exchangetokenAsync(resourceUri) {
            debugger;
            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);
            }
        }

        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>
    
const styleOptions = {
botAvatarInitials: 'BT',userAvatarInitials: 'UR',accent: '#00809d',botAvatarBackgroundColor: "#FFFFFF",userAvatarBackgroundColor:"#FFFFFF",hideUploadButton: true,};

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

        (async function main() {

            // Add your BOT ID below
            var BOT_ID = "<Bot ID>";
            var theURL = "https://powerva.microsoft.com/api/botmanagement/v1/directline/directlinetoken?botId=" + BOT_ID;
            
            var userId = clientApplication.account?.accountIdentifier != null ?
                ("You-customized-prefix" + clientApplication.account.accountIdentifier).substr(0,64)
                : (Math.random().toString() + Date.Now().toString()).substr(0,64);
                debugger;
            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') {
                    debugger;
                    dispatch({
                        type: 'WEB_CHAT/SEND_EVENT',payload: {
                            name: 'startConversation',type: 'event',value: { text: "hello" }
                        }
                    });
                    return next(action);
                }
                if (action.type === 'DIRECT_LINE/INCOMING_ACTIVITY') {
                    debugger;
                    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') {
                                            // bot 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);
            });

            window.WebChat.renderWebChat(
                {
                    directLine: directLine,store,userID: userId,styleOptions
                },document.getElementById('webchat')
            );
        })().catch(err => console.error("An error occurred: " + err));
    </script>
</body>
</html>

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)