【问题标题】:multiple_matching_tokens_detected with MSAL and JS使用 MSAL 和 JS 检测到的 multiple_matching_tokens_detected
【发布时间】:2020-11-04 00:05:06
【问题描述】:

我正在使用 react 构建 SPA,但我遇到了直接来自 Azure 门户 - Quickstart for Javascript 的代码问题。 (你可以在那里下载完整的代码)

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

但如果我在我的应用程序中使用相同的代码(它已经设置样式并且具有我需要的所有功能)它会给我在缓存中找到多个权限。在 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

【问题讨论】:

    标签: javascript reactjs azure azure-active-directory adal


    【解决方案1】:

    它给了我在缓存中找到的多个权限。传递权限 API 过载。|multiple_matching_tokens_detected` 错误,当我 验证

    此错误是因为 auth SDK 在缓存中为acquireTokenSilent 的输入找到多个匹配的令牌。

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

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

    【讨论】:

      【解决方案2】:

      只是为了回到它。我通过将整个项目移动到新的 create-react-app 来解决它。看起来有超过 1 个 MSAL 对象实例,因此同时有多个调用/令牌。

      奇怪但解决了我的问题。

      【讨论】:

        【解决方案3】:

        我知道这是一个老问题,但我还是会回答,因为我有同样的问题。

        我解决此问题的方法是在发生此错误时清除缓存。它适用于我的案例,因为这对于我的用例来说不是经常发生的错误。

        在我的项目配置中,该站点还设置为在发生此类错误时刷新并重试。因此,在清除缓存后,站点将重新加载并按预期工作,因为缓存中不会有冲突的令牌。

        import { AuthCache } from 'msal/lib-commonjs/cache/AuthCache';
        
        ...
        
        const authProvider = new MsalAuthProvider(
          configuration,
          authenticationParameters,
          msalProviderConfig,
        );
        
        authProvider.registerErrorHandler((authError: AuthError | null) => {
          if (!authError) {
            return;
          }
        
          console.error('Error initializing authProvider', authError);
        
          // This shouldn't happen frequently. The issue I'm fixing is that when upgrading from 1.3.0
          // to 1.4.3, it seems that the new version creates and stores a new set of auth credentials.
          // This results in the "multiple_matching_tokens" error.
          if (authError.errorCode === 'multiple_matching_tokens') {
            const authCache = new AuthCache(
              configuration.auth.clientId,
              configuration.cache.cacheLocation,
              configuration.cache.storeAuthStateInCookie,
            );
        
            authCache.clear();
        
            console.log(
              'Auth cache was cleared due to incompatible access tokens existing in the cache.',
            );
          }
        

        【讨论】:

          猜你喜欢
          • 2015-11-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多