2017-03-17 1 views
1

PowerBI 대시 보드를 고객 MVC 포털에 포함하려고합니다. 고객은 AAD 계정이 없으므로 웹 사이트에 올 때 Live에 로그인 할 수 없으므로 개별 권한으로 MVC 웹 사이트에 로그인합니다.PowerBI 및 Azure AD 헤드리스 로그인

PowerBI/AAD에 내 App을 등록하고 ClientID와 Secret을 가지고 있습니다. 나는 AAD에 전화를 걸어 인증 코드를 얻는다.이 코드를 사용하여 성공적으로 반환되는 인증 토큰을 얻는다.

액세스 토큰을 사용하여 대시 보드를 얻었을 때 403 금지됨과 함께 계속 거부됩니다.

Microsoft의 모든 샘플을 살펴 보았으나 사용자 로그인 프롬프트가 필요합니다. AcquireToken 메서드를 참조하는 ADAL2.0 코드를 검토했지만 ADAL3에서는 더 이상 사용되지 않으며 다른 매개 변수가있는 AcquireTokenAsync로 바뀌었고 아래 예제에서이 코드를 사용하고 있습니다.

protected AuthenticationResult GetAccessToken() 
    { 
     string pBiUser = Properties.Settings.Default.PowerBIUser; 
     string pBiPwd = Properties.Settings.Default.PowerBIPwd; 
     string pBiClientId = Properties.Settings.Default.PowerBIClientId; 
     string pBiSecret = Properties.Settings.Default.PowerBIClientSecret; 
     TokenCache TC = new TokenCache(); 
     ClientCredential CC = new ClientCredential(pBiClientId,pBiSecret); 
     string AU = Properties.Settings.Default.PowerBIAuthority; 
     Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext authenticationContext 
      = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(AU, TC); 
     AuthenticationResult result = authenticationContext.AcquireTokenAsync("https://analysis.windows.net/powerbi/api" 
      ,CC).Result; 

     if (result == null) 
     { 
      throw new InvalidOperationException("Failed to obtain the PowerBI token"); 
     } 

     return result; 
    } 

내가 다음 토큰 결과를 가지고 전화 : 여기

는 토큰을 얻을 수있는 기능입니다. 응답 수신 403 :

에러 메시지 ( 403) 기준
protected PBIDashboards GetDashboards(AuthenticationResult authResult) 
    { 
     PBIDashboards pbiDashboards = new PBIDashboards(); 
     var baseAddress = new Uri("https://api.powerbi.com"); 
     using (var httpClient = new System.Net.Http.HttpClient {BaseAddress = baseAddress}) 
     { 
      httpClient.DefaultRequestHeaders.TryAddWithoutValidation("authorization", 
       "Bearer " + authResult.AccessToken); 
      using (**var response** = httpClient.GetAsync("v1.0/myorg/dashboards").Result) 
      { 
       string responseData = response.Content.ReadAsStringAsync().Result; 

       //Deserialize JSON string 
       pbiDashboards = JsonConvert.DeserializeObject<PBIDashboards>(responseData); 

       if (pbiDashboards != null) 
       { 
        var gridViewDashboards = pbiDashboards.value.Select(dashboard => new 
        { 
         Id = dashboard.id, 
         DisplayName = dashboard.displayName, 
         EmbedUrl = dashboard.embedUrl 
        }); 
       } 
      } 
     } 
     return pbiDashboards; 
    } 
+0

여기서 정확한 질문은 무엇입니까? 사용자 인터페이스없이 사용자를 로그인하는 방법을 찾고 있습니까? –

답변

0

많은 연구 후에는 토큰을 얻기 위해 직접 AJAX 호출을 할 수 있습니다 : 당신이 문자열 AccessToken이 있으면

private async Task<string> GetAccessToken() 
    { 
     string pBiUser = Properties.Settings.Default.PowerBIUser; 
     string pBiPwd = Properties.Settings.Default.PowerBIPwd; 
     string pBiClientId = Properties.Settings.Default.PowerBIClientId; 
     string pBiSecret = Properties.Settings.Default.PowerBIClientSecret; 
     string pBITenant = Properties.Settings.Default.PowerBITenantId; 

     string tokenEndpointUri = "https://login.microsoftonline.com/"+pBITenant+"/oauth2/token"; 

     var content = new FormUrlEncodedContent(new[] 
      { 
     new KeyValuePair<string, string>("grant_type", "password"), 
     new KeyValuePair<string, string>("username", pBiUser), 
     new KeyValuePair<string, string>("password", pBiPwd), 
     new KeyValuePair<string, string>("client_id", pBiClientId), 
     new KeyValuePair<string, string>("client_secret", pBiSecret), 
     new KeyValuePair<string, string>("resource", "https://analysis.windows.net/powerbi/api") 
     }); 

     using (var client = new HttpClient()) 
     { 
      HttpResponseMessage res = client.PostAsync(tokenEndpointUri, content).Result; 

      string json = await res.Content.ReadAsStringAsync(); 

      AzureAdTokenResponse tokenRes = JsonConvert.DeserializeObject<AzureAdTokenResponse>(json); 

      return tokenRes.AccessToken; 
     } 
    } 

, 당신은 다음 대시 보드 요청을 호출 할 수 있습니다.

protected PBIDashboards GetDashboards(string token) 
    { 
     PBIDashboards pbiDashboards = new PBIDashboards(); 
     var baseAddress = new Uri("https://api.powerbi.com"); 
     using (var httpClient = new System.Net.Http.HttpClient {BaseAddress = baseAddress}) 
     { 
      httpClient.DefaultRequestHeaders.TryAddWithoutValidation("authorization", 
       "Bearer " + token); 
      using (var response = httpClient.GetAsync("v1.0/myorg/dashboards").Result) 
      { 
       string responseData = response.Content.ReadAsStringAsync().Result; 

       //Deserialize JSON string 
       pbiDashboards = JsonConvert.DeserializeObject<PBIDashboards>(responseData); 

       if (pbiDashboards != null) 
       { 
        var gridViewDashboards = pbiDashboards.value.Select(dashboard => new 
        { 
         Id = dashboard.id, 
         DisplayName = dashboard.displayName, 
         EmbedUrl = dashboard.embedUrl 
        }); 
       } 
      } 
     } 
     return pbiDashboards; 
    } 

이렇게하면 대시 보드의 목록과 자바 스크립트의 임베디드 페이지를 구축하기 위해 PowerBI API를 호출하는 대시 보드 ID를 제공합니다. 숨겨진 입력 필드를 사용하여 액세스 토큰을 저장하고 URL을 삽입하여 Javascript 호출에 전달했습니다.

// check if the embed url was selected 
var embedUrl = document.getElementById('embed').value; 
if (embedUrl === "") 
    return; 

// get the access token. 
accessToken = document.getElementById('token').value; 

// Embed configuration used to describe the what and how to embed. 
// This object is used when calling powerbi.embed. 
// You can find more information at https://github.com/Microsoft/PowerBI-JavaScript/wiki/Embed-Configuration-Details. 
var config = { 
    type: 'dashboard', 
    accessToken: accessToken, 
    embedUrl: embedUrl 
}; 

// Grab the reference to the div HTML element that will host the dashboard. 
var dashboardContainer = document.getElementById('dashboard'); 

// Embed the dashboard and display it within the div container. 
var dashboard = powerbi.embed(dashboardContainer, config); 
+0

안녕하세요. @ Rob. 인증 코드를 얻기 위해 단계를 건너 뛴다는 말씀입니까? – Shumii

0

, 문제가 허가에 대해이다.

AFAIK는 클라이언트 BI 자격 흐름을 사용하여 액세스 토큰을 획득 할 때 사용할 수있는 권한이 없습니다. 당신은 아래의 그림에 대한 권한을 참조 할 수 있습니다 :

enter image description here

사용자 상호 작용없이 전원 BI REST에 대한 토큰을 얻으려면, 우리는 자원 소유자 암호 자격 증명 흐름 사용할 수 있습니다. 그리고 이미 이것을 구현 한 타사 라이브러리 PowerBI.Api.Client을 사용할 수 있습니다.

+0

답변 해 주셔서 감사합니다. PowerBI.Api.Client에는 GetDashboards 메서드가 포함되어 있지 않습니다. Resource Owner Credential Flow에 대한 호출 및 자격 증명 프로세스가 있습니까? – Rob

+0

해당 타사 라이브러리를 사용하는 경우 해당 흐름에 대해 Fiddler를 사용하여 요청을 쉽게 캡처 할 수 있습니다. 또는 [link here] (https://blogs.msdn.microsoft.com/wushuai/2016/09/25/resource-owner-password-credentials-grant-in-azure-ad-oauth/)를 참조하십시오. 이 흐름의 세부 사항. –

+0

나는 여전히 유효한 인증 토큰을 얻을 수 없다. PowerBI. ADAL 3.0을 사용하여 PowerBI.Api를 살펴 보았다.위에서 언급 한 클라이언트이지만 ADAL3.0에서는 작동하지 않습니다. ADAL3에 더 이상 존재하지 않는 ADAL 2.0 AcquireToken 메서드를 사용합니다. 이것이 왜 변경되었는지 명확하지 않으며 clientId, secretId, username 및 password를 사용하여 유효한 토큰을 요청하는 직접적인 방법이 없습니다. 플로우와 피 들러를 살펴볼 때, 토큰을 얻는 것과 같은 비대화 형 메서드는 보이지 않습니다. 승인을 얻기 위해 제가 누락 된 것이 있어야합니다. – Rob