刷新令牌时adal.js inifnite循环

时间:2016-11-04 06:49:51

标签: adal.js

我正在使用最新的adal.js来查询MicroSoft Dynamics CRM中的数据。更新令牌时代码进入无限循环。

此外,在登录微软并重定向回我的页面后,adaljs会尝试刷新令牌。

注意 - 这是ASP.NET MVC Web应用程序中的javascript。使用角度js

这也与SO问题Adal & Adal-Angular - refresh token infinite loop

类似
var endpoints = {
    orgUri: "https://<tenant>.crm6.dynamics.com/"
};

var config = {
    clientId: 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX',
    tenant: '<tenant>.onmicrosoft.com',
    redirectUri: 'http://localhost:53290/home/AuthenticatedByCrm/',
    endpoints: endpoints,
    cacheLocation: 'localStorage'
};
var x = new AuthenticationContext(config);

var isCallback = x.isCallback(window.location.hash);

if (isCallback) {
    x.handleWindowCallback();
    x.acquireToken(endpoints.orgUri, retrieveAccounts);
} else {
    x.login();
}

function retrieveAccounts(error, token) {
    // Handle ADAL Errors.
    if (error || !token) {
        alert('ADAL error occurred: ' + error);
        return;
    }

    var req = new XMLHttpRequest();
    req.open("GET", encodeURI(organizationURI + "/api/data/v8.0/accounts?$select=name,address1_city&$top=10"), true);
    //Set Bearer token
    req.setRequestHeader("Authorization", "Bearer " + token);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.onreadystatechange = function () {
        if (this.readyState == 4 /* complete */) {
            req.onreadystatechange = null;
            if (this.status == 200) {
                var accounts = JSON.parse(this.response).value;
                //renderAccounts(accounts);
            }
            else {
                var error = JSON.parse(this.response).error;
                console.log(error.message);
                //errorMessage.textContent = error.message;
            }
        }
    };
    req.send();
}

1 个答案:

答案 0 :(得分:0)

Active Directory Authentication Library (ADAL) for JavaScript可帮助您使用Azure AD处理单页应用程序中的身份验证。 此库已针对与AngularJS 协同工作进行了优化。

根据调查,此问题是由handleWindowCallback引起的。响应无法进入if ((requestInfo.requestType === this.REQUEST_TYPE.RENEW_TOKEN) && window.parent && (window.parent !== window))的分支,因为它未在Angular环境中使用。

要将Azure AD与MVC应用程序集成,我建议您使用 Active Directory Authentication Library 。您可以参考代码示例here

更新

if (isCallback) {
     // x.handleWindowCallback();
     var requestInfo=x.getRequestInfo(window.location.hash);
     //get the token provided resource. to get the id_token, we need to pass the client id
     var token = x.getCachedToken("{clientId}")
     x.saveTokenFromHash(requestInfo);            
} else {
    x.login();
}