javascript - 使用 MSAL 和 JS 检测到 multiple_matching_tokens_Detected

标签 javascript reactjs azure azure-active-directory adal

我正在使用 React 构建 SPA,并且直接从 Azure 门户中遇到代码问题 - Quickstart for Javascript 。 (您可以在那里下载完整代码)

如果我创建-react-app并且使用代码,它工作得很好,我可以进行身份​​验证,获取 token 并在发布请求中使用它。

但是,如果我在我的应用程序中使用相同的代码(已经设计好样式并具有我需要的所有功能),它会为我提供在缓存中找到的多个权限。在 API 重载中传递权限。|当我进行身份验证时,出现 multiple_matching_tokens_detected` 错误。

只是为了澄清身份验证已通过,我看到我已通过身份验证,只是这个错误困扰着我,我不知道如何调试它。

function signIn() {

myMSALObj.loginPopup(applicationConfig.graphScopes).then(function (idToken) {
    //Login Success

    console.log(idToken); //note that I can get here!
    showWelcomeMessage();

    acquireTokenPopupAndCallMSGraph();
}, function (error) {
    console.log(error);
});

}

function acquireTokenPopupAndCallMSGraph() {
//Call acquireTokenSilent (iframe) to obtain a token for Microsoft Graph
myMSALObj.acquireTokenSilent(applicationConfig.graphScopes).then(function (accessToken) {
    callMSGraph(applicationConfig.graphEndpoint, accessToken, graphAPICallback);
}, function (error) {
    console.log(error); //this is where error comes from
    // Call acquireTokenPopup (popup window) in case of acquireTokenSilent failure due to consent or interaction required ONLY
    if (error.indexOf("consent_required") !== -1 || error.indexOf("interaction_required") !== -1 || error.indexOf("login_required") !== -1) {
        myMSALObj.acquireTokenPopup(applicationConfig.graphScopes).then(function (accessToken) {
            callMSGraph(applicationConfig.graphEndpoint, accessToken, graphAPICallback);
        }, function (error) {
            console.log(error);
        });
    }
});

}

我不明白的主要事情是,相同的代码在新的 create-react-app 项目中工作得很好,但是当我在已经存在的项目中使用它时(只是没有身份验证),它会因提到的错误而中断。

完整代码

import React, { Component } from 'react'
import * as Msal from 'msal'

export class test extends Component {

    render() {

var applicationConfig = {
    clientID: '30998aad-bc60-41d4-a602-7d4c14d95624', //This is your client ID
    authority: "https://login.microsoftonline.com/35ca21eb-2f85-4b43-b1e7-6a9f5a6c0ff6", //Default authority is https://login.microsoftonline.com/common
    graphScopes: ["30998aad-bc60-41d4-a602-7d4c14d95624/user_impersonation"],
    graphEndpoint: "https://visblueiotfunctionapptest.azurewebsites.net/api/GetDeviceList"
};

var myMSALObj = new Msal.UserAgentApplication(applicationConfig.clientID, applicationConfig.authority, acquireTokenRedirectCallBack,
    {storeAuthStateInCookie: true, cacheLocation: "localStorage"});

function signIn() {

    myMSALObj.loginPopup(applicationConfig.graphScopes).then(function (idToken) {
        //Login Success

        console.log(idToken);
        showWelcomeMessage();

        acquireTokenPopupAndCallMSGraph();
    }, function (error) {
        console.log(error);
    });
}

function signOut() {
    myMSALObj.logout();
}

function acquireTokenPopupAndCallMSGraph() {
    //Call acquireTokenSilent (iframe) to obtain a token for Microsoft Graph
    myMSALObj.acquireTokenSilent(applicationConfig.graphScopes).then(function (accessToken) {
        callMSGraph(applicationConfig.graphEndpoint, accessToken, graphAPICallback);
    }, function (error) {
        console.log(error);
        // Call acquireTokenPopup (popup window) in case of acquireTokenSilent failure due to consent or interaction required ONLY
        if (error.indexOf("consent_required") !== -1 || error.indexOf("interaction_required") !== -1 || error.indexOf("login_required") !== -1) {
            myMSALObj.acquireTokenPopup(applicationConfig.graphScopes).then(function (accessToken) {
                callMSGraph(applicationConfig.graphEndpoint, accessToken, graphAPICallback);
            }, function (error) {
                console.log(error);
            });
        }
    });
}


function callMSGraph(theUrl, accessToken, callback) {
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200)
            callback(JSON.parse(this.responseText));
            console.log(this.response);
    }
    xmlHttp.open("POST", theUrl, true); // true for asynchronous
    xmlHttp.setRequestHeader('Authorization', 'Bearer ' + accessToken);
    var dataJSON = JSON.stringify({ userEmail: null, FromDataUTC: "2012-04-23T18:25:43.511Z" })
    xmlHttp.send(dataJSON);
}

function graphAPICallback(data) {
    //Display user data on DOM
    // var divWelcome = document.getElementById('WelcomeMessage');
    // divWelcome.innerHTML += " to Microsoft Graph API!!";
    // document.getElementById("json").innerHTML = JSON.stringify(data, null, 2);
}

function showWelcomeMessage() {
    console.log("You are looged: " + myMSALObj.getUser().name);
    // var divWelcome = document.getElementById('WelcomeMessage');
    // divWelcome.innerHTML += 'Welcome ' + myMSALObj.getUser().name;
    // var loginbutton = document.getElementById('SignIn');
    // loginbutton.innerHTML = 'Sign Out';
    // loginbutton.setAttribute('onclick', 'signOut();');
}

// This function can be removed if you do not need to support IE
function acquireTokenRedirectAndCallMSGraph() {
    //Call acquireTokenSilent (iframe) to obtain a token for Microsoft Graph
    myMSALObj.acquireTokenSilent(applicationConfig.graphScopes).then(function (accessToken) {
      callMSGraph(applicationConfig.graphEndpoint, accessToken, graphAPICallback);
    }, function (error) {
        console.log(error);
        //Call acquireTokenRedirect in case of acquireToken Failure
        if (error.indexOf("consent_required") !== -1 || error.indexOf("interaction_required") !== -1 || error.indexOf("login_required") !== -1) {
            myMSALObj.acquireTokenRedirect(applicationConfig.graphScopes);
        }
    });
}

function acquireTokenRedirectCallBack(errorDesc, token, error, tokenType)
{
 if(tokenType === "access_token")
 {
     callMSGraph(applicationConfig.graphEndpoint, token, graphAPICallback);
 } else {
        console.log("token type is:"+tokenType);
 }

}

// Browser check variables
var ua = window.navigator.userAgent;
var msie = ua.indexOf('MSIE ');
var msie11 = ua.indexOf('Trident/');
var msedge = ua.indexOf('Edge/');
var isIE = msie > 0 || msie11 > 0;
var isEdge = msedge > 0;

//If you support IE, our recommendation is that you sign-in using Redirect APIs
//If you as a developer are testing using Edge InPrivate mode, please add "isEdge" to the if check
if (!isIE) {
    if (myMSALObj.getUser()) {// avoid duplicate code execution on page load in case of iframe and popup window.
        showWelcomeMessage();
        acquireTokenPopupAndCallMSGraph();
    }
}
else {
    document.getElementById("SignIn").onclick = function () {
        myMSALObj.loginRedirect(applicationConfig.graphScopes);
    };

    if (myMSALObj.getUser() && !myMSALObj.isCallback(window.location.hash)) {// avoid duplicate code execution on page load in case of iframe and popup window.
        showWelcomeMessage();
        acquireTokenRedirectAndCallMSGraph();
    }
}

    return (
        <div>

        <h2>Please log in from VisBlue app</h2>
        <button id="SignIn" onClick={signIn}>Sign In</button>
        <button id="SignOut" onClick={signOut}>Sign Out</button>
        <h4 id="WelcomeMessage"></h4>

        <br/><br/>
        <pre id="json"></pre>
            </div>
    )
  }
}

export default test

最佳答案

it gives me Multiple authorities found in the cache. Pass authority in the API overload.|multiple_matching_tokens_detected` error when I authenticate

导致此错误的原因是 auth SDK 在缓存中为 acquireTokenSilent 的输入找到了多个匹配 token 。 。

尝试添加权限,并在必要时添加用户:

  myMSALObj
    .acquireTokenSilent(
      applicationConfig.graphScopes,
      applicationConfig.authority
    )
    .then(
    ...

关于javascript - 使用 MSAL 和 JS 检测到 multiple_matching_tokens_Detected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55419542/

相关文章:

javascript - 如何在日期时间选择器中使用两个验证器

javascript - react 中的单选按钮,忽略空值

javascript - 使用 nextjs 在同一页面上链接页面

reactjs - 如何在 react 排序树的特定节点中添加按钮

java - 错误: opening Service Client using correct connection string

azure - 在 Azure 上的 GitHub 工作流中应用 EF 迁移

javascript - 使用 Java 或 JavaScript 将 HTML 页面与 CSS 一起转换为 PDF

javascript - 无法使用document.getElementById().innerHTML重写原始html

visual-studio-2010 - 如何配置 Azure 角色以使用自定义端口连接到 Windows Azure 存储模拟器?

javascript - Jquery 触发主体调整大小