2017-12-16 25 views
0

ios/android 용 Cordova 앱을 만들었습니다. 이 응용 프로그램은 Azure Active Directory에 연결된 Azure 모바일 서비스를 사용합니다. 이것은 잘 작동합니다. 디렉터리 검색을 시도 할 때 Azure에서 내 거주자 자격 증명을 사용하여 인증하라는 메시지가 나타납니다.Cordova Azure에서 Azure Web API를 쿼리하는 방법 인증 된 앱

다음 단계 :

우리는 푸른 SQL 데이터베이스에 대한 몇 가지 C.R.U.D을 가지고 몇 가지 API를 가지고있다. API는 정상적으로 작동하며 https://mat.azurewebsites.net/api/values으로 이동하여 데이터를 가져옵니다 (보안 설정되지 않은 상태에서).

사용자가 ADAL Cordova 라이브러리를 사용하여 인증했으면 (정상적으로 작동하고 토큰을 다시 받음) 웹 API에 대한 GET 요청을 실행하고 데이터를 반환하고 싶습니다. 나는 문제가 있으며

우리는 비슷한 질문이 How do I query Azure Web API from Cordova Azure Authenticated app

여기에 게시하지만 아무 대답이있을 수 있도록 API에 요청을 구성하는 방법을 잘 아니에요 곳입니다

.

여러 apis를 호출해야합니다. AngularJs adal에서 여러 끝점을 전달할 수 있지만 여기에서는 전달할 수있는 방법을 알지 못합니다.

var authority = "https://login.microsoftonline.com/TenantId", 

redirectUri = "https://Mobile", 

resourceUri = "https://graph.microsoft.com" // I am not sure what should be here, 

clientId = "xxxxxxxxxxxxxxx"; 


var url = "https://xxxxx-api.cloudapp.net/v1/purchaseorders? 
$orderby=OrderPlacementDate desc" 

req.open("GET", url, true); 
    req.setRequestHeader('Authorization', 'Bearer ' + 
authResult.accessToken); 
    req.setRequestHeader('XXX.FunctionGroup', 'PurchaseProduct'); 

    req.onload = function (e) { 
     if (e.target.status >= 200 && e.target.status < 300) { 
      app.error('Valid'); 

      app.renderData(JSON.parse(e.target.response)); 
      return; 
     } 
     app.error('Data request failed error: ' + e.target.response + '.......' + e.target.status); 
    }; 
    req.onerror = function (e) { 
     app.error('Data request failed onerror: ' + e); 
    } 

    req.send(); 

@@@@@@ 이 가 인증합니다

당신은 무기명 토큰으로 HTTP 인증 헤더에 토큰을 전달해야
authenticate: function (authCompletedCallback) { 

    app.context = new Microsoft.ADAL.AuthenticationContext(authority); 
    app.context.tokenCache.readItems().then(function (items) { 


     if (items.length > 0) { 
      authority = items[0].authority; 
      app.context = new Microsoft.ADAL.AuthenticationContext(authority); 
     } 
     // Attempt to authorize user silently 
     app.context.acquireTokenSilentAsync(resourceUri, clientId) 
      .then(authCompletedCallback, function() { 
       // We require user cridentials so triggers authentication dialog 
       app.context.acquireTokenAsync(resourceUri, clientId, redirectUri) 
        .then(authCompletedCallback, function (err) { 
         app.error("Failed to authenticate: " + err); 
        }); 
      }); 
    }); 

} 
+0

당신은 당신의 API 호출에 토큰을 전달해야합니다. – singh

+0

예제가 있습니까? 질문 설명에 약간의 코드를 추가하고 있습니다. –

+0

var mytoken = "token get"을 설정 한 다음 apiurl/endpoint? token = mytoken과 다른 작업을 수행하십시오. 유효성 검사 토큰을받는 경우 유효성을 검사합니다. 나는 그것이 어떻게 든 실패하고있는 무기명을 지정할 때 의심하고 있습니다. – singh

답변

-1

코드입니다. "Bearer TOKEN"형식으로

Postman에서 HTTP 호출을 테스트하여 HTTP GET 요청을 작성하여 응용 프로그램의 토큰을 토큰 앞에 "무기명"이있는 권한 헤더에 복사합니다.

// Makes an API call to receive the user list 
requestData: function (authResult, searchText) { 
    var req = new XMLHttpRequest(); 
    var url = resourceUri + "/" + authResult.tenantId + 
"/users?api-version=" + graphApiVersion; 
    url = searchText ? url + "&$filter=mailNickname eq '" + 
searchText + "'" : url + "&$top=10"; 

    req.open("GET", url, true); 
    req.setRequestHeader('Authorization', 'Bearer ' + 
authResult.accessToken); 

    req.onload = function(e) { 
     if (e.target.status >= 200 && e.target.status < 300) { 
      app.renderData(JSON.parse(e.target.response)); 
      return; 
     } 
     app.error('Data request failed: ' + e.target.response); 
    }; 
    req.onerror = function(e) { 
     app.error('Data request failed: ' + e.error); 
    } 

    req.send(); 
}, 

https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-devquickstarts-cordova

+0

나는 보안 API가 아니라는 것을 의심하고 그게 내가 404를 얻는 이유이다. (하지만 이것은 추측이다.) 누구든지 코드에서 무엇을해야 호출 할 수 있는지, 특히 Android 앱에서 모바일 앱의 보안되지 않은 API의 데이터입니다. –

+0

API가 보호되지 않으면 권한 부여 요청 헤더가 무시됩니다. 404가 잘못된 URL로 인해 의심됩니다. URL의 검색어 문자열 섹션이 맞는지 확인하십시오. $ orderby = OrderPlacementDate desc –

+0

예 ... SSL로 인해 404를 얻었고 코드바 플러그인 허용 목록을 추가 한 후이를 해결했습니다. 이제 여러 레지오리 (동일한 거주자)가 토큰을 생성하는 가장 좋은 방법이 무엇인지 알고 싶습니다. 설명에 코드를 추가했습니다. 루프에 코드를 추가해야합니까 아니면 ...? –