2017-10-18 7 views
1

이 발생했습니다. Azure AD 인증 웹 API를 구현했으며 ADAL 1.0.12 (자동 로그인을 위해 iframe을 처리하기 위해 자체 wrapper가 있습니다.)ADAL.js 시간 초과로 인해 Azure AD Auth 웹 API

이제 래퍼를 모두 없애고 최신 버전으로 업그레이드하고 여기서 설명한 문제를 시작했습니다. 토큰 갱신 작업 시간이 초과되었습니다.

API 뒤에있는 Azure AD 아키텍처는 매우 간단합니다. 디렉토리 데이터 읽기 및 로그인 및 사용자 프로필 사용 권한 읽기가있는 등록 된 웹 앱입니다. 우리는 웹 앱에 대한 권한으로 등록 된 다른 네이티브 앱을 가지고 있습니다 (웹 APP 네임 액세스). 두 응용 프로그램 모두 해당 manifest에서 oauth2AllowImplicitFlow를 true로 설정합니다.

두 앱 모두 https://ourtenant.sharepoint.com/ *에 대한 와일드 카드 리디렉션 URI를 등록했습니다. 우리는 SharePoint에서 웹 API로 전화를 걸고 있습니다. 또한 기본 클라이언트 앱은 웹 API 앱의 고유 URI (앱 ID URI)에 리디렉션 URI를 등록했습니다.

두 애플리케이션은 전에 관리자의 동의를 부여받은 - 그들은 ADAL.js

의 이전 버전과 잘 작동하고 그래서, 여기에 몇 가지 코드입니다. displayCall 콜백 (현재 페이지에서 직접 페이지를 새로 고침)과 페이지 새로 고침 (initLogin 메서드의 주석 처리 된 코드 확인)을 모두 시도하지 않았 음을 유의하십시오. 또한 성공적인 로그인시 콜백을 사용하여 팝업 또는 iframe을 생성하는 스위치가 있습니다.

문제는 authContext.acquireToken입니다. OurNamespace.authContext.getCachedToken (OurNamespace.clientId)를 호출하면 리소스에 대해 저장된 토큰을 얻습니다.

각 페이지 새로 고침/iframe/팝업 후에 handleWindowCallback을 제대로 호출한다는 점에 유의하십시오.

브라우저와 관계없이 발생합니다.

OurNamespace = { 

serviceMainUrl: "https://localhost:44339", 
webApiAppIdUri: "WEB-API-URI", 
tenant: "TENANT", 
clientId: "NATIVE-APP-GUID", // Native APP 
adalEndPoints: { 
    get: null 
}, 
adal: null, 
authContext: null, 
dummyAuthPage: null, 
usePopup: true, 

init: function() { 
    this.dummyAuthPage = "DummmyLogin.aspx"; 
    OurNamespace.adalEndPoints.get = OurNamespace.serviceMainUrl + "/api/values"; 
    OurNamespace.authContext = new AuthenticationContext({ 
     tenant: OurNamespace.tenant + '.onmicrosoft.com', 
     clientId: OurNamespace.clientId, 
     webApiAppIdUri: OurNamespace.webApiAppIdUri, 
     endpoints: OurNamespace.adalEndPoints, 
     popUp: false, 
     postLogoutRedirectUri: window.location.origin, 
     cacheLocation: "localStorage", 
     displayCall: OurNamespace.displayCall, 
     redirectUri: _spPageContextInfo.siteAbsoluteUrl + "/Pages/" + OurNamespace.dummyAuthPage 
    }); 
    var user = OurNamespace.authContext.getCachedUser(); // OurNamespace.authContext.getCachedToken(OurNamespace.clientId) 
    if (user) { 
     OurNamespace.azureAdAcquireToken(); 
    } else { 
     OurNamespace.initLogin(); 
    } 
}, 

initLogin: function() { 
    //OurNamespace.authContext.config.displayCall = null; 
    //var isCallback = OurNamespace.authContext.isCallback(window.location.hash); 
    //OurNamespace.authContext.handleWindowCallback(); 

    //if (isCallback && !OurNamespace.authContext.getLoginError()) { 
    // window.location.href = OurNamespace.authContext._getItem(OurNamespace.authContext.CONSTANTS.STORAGE.LOGIN_REQUEST); 
    //} 

    OurNamespace.authContext.login(); 
}, 

displayCall: function (url) { 
    var iframeId = "azure-ad-tenant-login", 
     popup = null; 
    if (OurNamespace.usePopup) { 
     popup = window.open(url, 'auth-popup', 'width=800,height=500'); 
    } else { 
     var iframe = document.getElementById(iframeId); 
     if (!iframe) { 
      iframe = document.createElement("iframe"); 
      iframe.setAttribute('id', iframeId); 
      document.body.appendChild(iframe); 
     } 
     iframe.style.visibility = 'hidden'; 
     iframe.style.position = 'absolute'; 
     iframe.src = url; 
     popup = iframe.contentDocument; 
    } 
    var intervalId = window.setInterval(function() { 
     try { 
      // refresh the contnetDocument for iframe 
      if (!OurNamespace.usePopup) 
       popup = iframe.contentDocument; 
      var isCallback = OurNamespace.authContext.isCallback(popup.location.hash); 
      OurNamespace.authContext.handleWindowCallback(popup.location.hash); 
      if (isCallback && !OurNamespace.authContext.getLoginError()) { 
       popup.location.href = OurNamespace.authContext._getItem(OurNamespace.authContext.CONSTANTS.STORAGE.LOGIN_REQUEST); 
       window.clearInterval(intervalId); 
       if (OurNamespace.usePopup) { 
        popup.close(); 
       } 
       var user = OurNamespace.authContext.getCachedUser(); 
       if (user) { 
        console.log(user); 
       } else { 
        console.error(OurNamespace.authContext.getLoginError()); 
       } 
      } 
     } catch (e) { } 
    }, 400); 
}, 

azureAdAcquireToken: function() { 
    OurNamespace.authContext.acquireToken(OurNamespace.adalEndPoints.get, function (error, token) { 
     if (error || !token) { 
      SP.UI.Status.addStatus("ERROR", ('acquireToken error occured: ' + error), true); 
      return; 
     } else { 
      OurNamespace.processWebApiRequest(token); 
     } 
    }); 
}, 

processWebApiRequest: function (token) { 
    // Alternatively, in MVC you can retrieve the logged in user in the web api with HttpContext.Current.User.Identity.Name 
    $.ajax({ 
     type: "GET", 
     url: OurNamespace.adalEndPoints.get, 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     data: {}, 
     headers: { 
      'Authorization': 'Bearer ' + token 
     }, 
     success: function (results) { 
      var dataObject = JSON.parse(results); 
      SP.UI.Status.addStatus("Info", "ADAL GET data success: " + dataObject.webApiUser); 
      $(".grid-info").html("<h1 class=\"h1\">Current Web API authenticated user: " + dataObject.webApiUser + "</h1>"); 
     }, 
     error: function (xhr, errorThrown, textStatus) { 
      console.error(xhr); 
      SP.UI.Status.addStatus("ERROR", ('Service error occured: ' + textStatus), true); 
     } 
    }); 
} 
} 

답변

0

사실 숨기기은 iframe하여 액세스 토큰을 획득하기 위해 this._renewToken(resource, callback)를 호출되는 authContext.acquireToken를 사용하여 토큰을 성공적으로 액세스를 1.0.15 adal.js를 사용하여 얻을 테스트입니다.

<html> 
 
<head> 
 

 
<script src="/js/1.0.15/adal.js"></script> 
 
<script> 
 

 
var config = { 
 
    tenant: 'adfei.onmicrosoft.com', 
 
    clientId: '7e3b0f81-cf5c-4346-b3df-82638848104f', 
 
    redirectUri: 'http://localhost/spa.html', 
 
    navigateToLoginRequestUrl:false, 
 

 
}; 
 

 
var authContext=new AuthenticationContext(config); 
 

 
var hash = window.location.hash; 
 

 
if(hash.length!=0){ 
 
    authContext.handleWindowCallback(hash); 
 
    var user=authContext.getCachedUser(); 
 
} 
 
    
 

 
function login(){ 
 
    authContext.login(); 
 
} 
 

 
function acqureToken(){ 
 
    authContext.acquireToken("https://graph.microsoft.com", function(error, token, message){ 
 
     console.log(token) 
 

 
    }) 
 
} 
 

 
</script> 
 
</head> 
 

 
<body> 
 
<button onclick="login()">Login</button> 
 
<button onclick="acqureToken()">AcquireToken</button> 
 

 
</body> 
 
</html>

것이 도움이된다 여기 참조에 대한 전체 테스트 샘플 코드는? 또는이 문제에 대해 실행할 수있는 코드 샘플을 공유 하시겠습니까?

0

사용중인 adal.js의 버전이 확실하지 않습니다. 그러나 밀리 초 단위로 설정할 수있는 config 개체의 loadFrameTimeout 설정이 있습니다. adal.js 파일의 맨 위를 확인하면 거기에 있어야합니다.