Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 检测到多个与MSAL和JS匹配的令牌_Javascript_Reactjs_Azure_Azure Active Directory_Adal - Fatal编程技术网

Javascript 检测到多个与MSAL和JS匹配的令牌

Javascript 检测到多个与MSAL和JS匹配的令牌,javascript,reactjs,azure,azure-active-directory,adal,Javascript,Reactjs,Azure,Azure Active Directory,Adal,我正在使用react构建SPA,但直接从Azure Portal生成的代码遇到了问题-。(你可以在那里下载完整的代码) 如果我创建react应用程序并使用代码,它工作正常,我可以进行身份验证,获取令牌并在post请求中使用它 但是,如果我在我的应用程序中使用相同的代码(已经设计好了样式,并且具备了我所需要的所有功能),它会给我在缓存中找到的多个权限。在API重载中传递权限。|多个_匹配_令牌_检测到`身份验证时出错。 只是为了澄清身份验证通过了,我看到我被身份验证了,只是这个错误困扰着我,我不知

我正在使用react构建SPA,但直接从Azure Portal生成的代码遇到了问题-。(你可以在那里下载完整的代码)

如果我创建react应用程序并使用代码,它工作正常,我可以进行身份验证,获取令牌并在post请求中使用它

但是,如果我在我的应用程序中使用相同的代码(已经设计好了样式,并且具备了我所需要的所有功能),它会给我在缓存中找到的多个权限。在API重载中传递权限。|多个_匹配_令牌_检测到`身份验证时出错。

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

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);
});
}

}

我不明白的主要一点是,相同的代码在fresh create react应用程序项目中工作得很好,但当我在一个已经存在的项目中使用它时(只是没有身份验证),它会因提到的错误而中断

完整代码

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
import React,{Component}来自“React”
从“Msal”导入*作为Msal
导出类测试扩展组件{
render(){
var应用程序配置={
clientID:'30998aad-bc60-41d4-a602-7d4dc14d95624',//这是您的客户ID
权限:“https://login.microsoftonline.com/35ca21eb-2f85-4b43-b1e7-6a9f5a6c0ff6“,//默认权限为https://login.microsoftonline.com/common
图形范围:[“30998aad-bc60-41d4-a602-7d4c14d95624/用户模拟”,
graphEndpoint:“https://visblueiotfunctionapptest.azurewebsites.net/api/GetDeviceList"
};
var myMSALObj=新的Msal.UserAgentApplication(applicationConfig.clientID、applicationConfig.authority、acquireTokenRedirectCallBack、,
{storeauthstateincokie:true,cacheLocation:“localStorage”});
函数签名(){
myMSALObj.loginPopup(applicationConfig.graphScopes)。然后(函数(idToken){
//登录成功
console.log(idToken);
showWelcomeMessage();
acquireTokenPopupAndCallMSGraph();
},函数(错误){
console.log(错误);
});
}
函数签出(){
myMSALObj.logout();
}
函数acquireTokenPopupAndCallMSGraph(){
//调用acquireTokenSilent(iframe)以获取Microsoft Graph的令牌
myMSALObj.acquireTokenSilent(applicationConfig.graphScopes)。然后(函数(accessToken){
callMSGraph(applicationConfig.graphEndpoint、accessToken、GraphHapiCallback);
},函数(错误){
console.log(错误);
//如果AcquireTokenSumment因同意或仅需要交互而失败,请调用acquireTokenPopup(弹出窗口)
if(error.indexOf(“需要同意”)!=-1 | | error.indexOf(“需要互动”)!=-1 | | error.indexOf(“需要登录”)!=-1){
acquireTokenPopup(applicationConfig.graphScopes)。然后(函数(accessToken){
callMSGraph(applicationConfig.graphEndpoint、accessToken、GraphHapiCallback);
},函数(错误){
console.log(错误);
});
}
});
}
函数callMSGraph(URL、accessToken、回调){
var xmlHttp=new XMLHttpRequest();
xmlHttp.onreadystatechange=函数(){
if(this.readyState==4&&this.status==200)
回调(JSON.parse(this.responseText));
console.log(this.response);
}
open(“POST”,theUrl,true);//对于异步
setRequestHeader('Authorization','Bearer'+accessToken);
var dataJSON=JSON.stringify({userEmail:null,FromDataUTC:“2012-04-23T18:25:43.511Z”})
send(dataJSON);
}
函数图hapicallback(数据){
//在DOM上显示用户数据
//var divWelcome=document.getElementById('WelcomeMessage');
//divWelcome.innerHTML+=“到Microsoft图形API!!”;
//document.getElementById(“json”).innerHTML=json.stringify(数据,null,2);
}
函数showWelcomeMessage(){
log(“您正在出血:+myMSALObj.getUser().name”);
//var divWelcome=document.getElementById('WelcomeMessage');
//divWelcome.innerHTML+='Welcome'+myMSALObj.getUser().name;
//var loginbutton=document.getElementById('SignIn');
//loginbutton.innerHTML='注销';
//setAttribute('onclick','signOut();');
}
//如果您不需要支持IE,则可以删除此功能
函数acquireTokenRedirectAndCallMSGraph(){
//调用acquireTokenSilent(iframe)以获取Microsoft Graph的令牌
myMSALObj.acquireTokenSilent(applicationConfig.graphScopes)。然后(函数(accessToken){
callMSGraph(applicationConfig.graphEndpoint、accessToken、GraphHapiCallback);
},函数(错误){
console.log(错误);
//在acquireToken失败时调用acquireTokenRedirect
if(error.indexOf(“需要同意”)!=-1 | | error.indexOf(“需要互动”)!=-1 | | error.indexOf(“需要登录”)!=-1){
myMSALObj.acquireTokenRedirect(应用程序配置图形示波器);
}
});
}
函数acquireTokenRedirectCallBack(errorDesc,token,error,tokenType)
{
if(令牌类型==“访问令牌”)
{
callMSGraph(applicationConfig.graphEndpoint、token、graphAPICallback);
}否则{
console.log(“令牌类型为:”+tokenType);
}
}
//浏览器检查变量
var ua=window.navigator.userAgent;
var msie=ua.indexOf('msie');
变量msie11=ua.indexOf('Trident/');
var msedge=ua.indexOf('Edge/');
变量isIE=msie>0 | | msie11>0;
var isEdge=msedge>0;
//如果您支持IE,我们建议您使用重定向API登录
//如果您作为开发人员正在使用Edge InPrivate模式进行测试,请将“iEdge”添加到If检查中
如果(!isIE){
if(myMSALObj.getUser()){//避免在iframe和弹出窗口的情况下在页面加载时重复执行代码。
showWelcomeMessage();
acquireTokenPopupAndCallMSGraph();
}
}
否则{
document.getElementById(“SignIn”).onclick=function(){
myMSALObj.loginDirect(应用程序)
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
  myMSALObj
    .acquireTokenSilent(
      applicationConfig.graphScopes,
      applicationConfig.authority
    )
    .then(
    ...
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.',
    );
  }