2016-08-17 3 views
1

AAD를 사용하여 클라이언트를 인증하고 Windows 서비스를 사용하여 자동화하려고합니다. AAD의 .NET의 SDK에서는이 두 가지 방법, AcquireTokenAsyncAcquireToken하지만 나는 await를 호출, 응답이 영원히 남아있을 것입니다 이러한 방법 중 하나를 사용할 수 없습니다와 나는 같은 것을 수행 할 때사용자 이름 및 암호로 Azure Active Directory 토큰 가져 오기

result = authContext.AcquireTokenAsync(resourceHostUri, clientId, new UserCredential(hardcodedUsername, hardcodedPassword)).Result; 

을 개체는 Waiting for Activation 상태를 반환합니다. & Code 31 ..

이제 하드 코드 된 사용자 이름과 암호를 사용하여 토큰을 획득 할 수 있습니까?

내 전체 코드 :

 string hardcodedUsername = "username"; 
     string hardcodedPassword = "password"; 

     string tenant = "[email protected]"; 
     string clientId = "clientId"; 
     string resourceHostUri = "https://management.azure.com/"; 
     string aadInstance = "https://login.microsoftonline.com/{0}"; 

     string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant); 


     authContext = new AuthenticationContext(authority); 

     AuthenticationResult result = null; 
      try 
      { 

       result = authContext.AcquireTokenAsync(resourceHostUri, clientId, new UserCredential(hardcodedUsername, hardcodedPassword)).Result; 
      } 
      catch (Exception ex) 
      { 
       System.Diagnostics.Debug.WriteLine(ex.Message); 
      } 

      return result; 

나는 푸른 API에 대한 액세스 권한을 얻기 위해 노력하고있어.

UPDATE 1 :

Microsoft.IdentityModel.Clients.ActiveDirectory TokenCache을 :

내가 await에 전화를 시도 할 때 I 출력이있어, 나는이 도움이 될 생각 찾고 ... Microsoft.IdentityModel.Clients.ActiveDirectory TokenCache : 캐시에서 일치하는 토큰을 찾을 수 없습니다. Microsoft.IdentityModel.Clients.ActiveDirectory d__0 : 사용자 영역 검색 요청을 ''(으)로 보내는 중입니다.이름 API 버전 = 1.0 ' Microsoft.IdentityModel.Clients.ActiveDirectory의 d__4 : 해시와 사용자? *** 링크 코드 아래 연합'

+0

'async' 메소드를 만들고'authContext.AcquireTokenAsync()'메소드 호출 앞에'await'을 넣으려고 했습니까? –

+0

예, 응답이 없으면 영원히 걸립니다. 제 질문에 언급했습니다. –

+0

메서드 서명과이 메서드 호출 방법을 포함하여 전체 코드를 공유 할 수 있습니까? –

답변

0

시도 '로 감지'

https://msdn.microsoft.com/en-in/library/partnercenter/dn974935.aspx

how to get access token after windows azure active directory authentication

How to get current token from Azure ActiveDirectory application

// Get OAuth token using client credentials 
string tenantName = "GraphDir1.OnMicrosoft.com"; 
string authString = "https://login.microsoftonline.com/" + tenantName; 

AuthenticationContext authenticationContext = new AuthenticationContext(authString, false); 

// Config for OAuth client credentials 
string clientId = "118473c2-7619-46e3-a8e4-6da8d5f56e12"; 
string key = "hOrJ0r0TZ4GQ3obp+vk3FZ7JBVP+TX353kNo6QwNq7Q="; 
ClientCredential clientCred = new ClientCredential(clientId, key); 
string resource = "https://graph.windows.net"; 
string token; 
try 
{ 
    AuthenticationResult authenticationResult = authenticationContext.AcquireToken(resource, clientCred); 
    token = authenticationResult.AccessToken; 
} 
catch (AuthenticationException ex) 
{ 
    Console.ForegroundColor = ConsoleColor.Red; 
    Console.WriteLine("Acquiring a token failed with the following error: {0}", ex.Message); 
    if (ex.InnerException != null) 
    { 
     // You should implement retry and back-off logic according to 
     // http://msdn.microsoft.com/en-us/library/dn168916.aspx . This topic also 
           // explains the HTTP error status code in the InnerException message. 
     Console.WriteLine("Error detail: {0}", ex.InnerException.Message); 
    } 
} 
+0

2 가지입니다 : 1) OP는 클라이언트 자격 증명을 사용하지 않고 사용자 이름/비밀번호 조합을 사용하여 자격 증명을 가져 오려고합니다. 2) OP는 비동기 메소드를 사용합니다. 당신이 보여 주신 것은 동기화 방법이며 클라이언트 인증서를 사용하고 있습니다. –

+0

정확히 AAD의 응용 프로그램이 Native Client이므로 인증 정보 (사용자 이름 및 암호)를 사용하려면 이런 종류의 인증을 수행 할 수있는 키를 얻을 수 없습니다. –

0

다음을 시도하십시오 :

getAccessToken() 방법 async을 만들어 코드가 당신이 authContext.AcquireTokenAsync를 호출 할 때 토큰을 얻기 위해 기다리게되는 내부 내가 무슨 짓을
static void Main(string[] args) 
    { 
     Task<AuthenticationResult> t = getAccessToken(); 
     t.Wait(); 
     var result = t.Result; 
     Console.WriteLine(result.AccessToken); 
     Console.WriteLine("Please any key to terminate the program"); 
     Console.ReadKey(); 
    } 

    public static async Task<AuthenticationResult> getAccessToken() 
    { 
     string hardcodedUsername = "username"; 
     string hardcodedPassword = "password"; 

     string tenant = "tenant.onmicrosoft.com"; 
     string clientId = "clientId"; 
     string resourceHostUri = "https://management.azure.com/"; 
     string aadInstance = "https://login.microsoftonline.com/{0}"; 

     string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant); 


     var authContext = new AuthenticationContext(authority); 

     AuthenticationResult result = null; 
     try 
     { 
      result = await authContext.AcquireTokenAsync(resourceHostUri, clientId, new UserCredential(hardcodedUsername, hardcodedPassword)); 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine(ex.StackTrace); 
      System.Diagnostics.Debug.WriteLine(ex.Message); 
     } 

     return result; 
    } 

.

+0

이전에 시도했지만 아무 것도 기다리지 않았습니다. 응답,하지만 이번엔 내가 출력을 확인, 거기에 흥미로운 .. 내가 출력을 볼 수 있도록 내 질문을 편집했습니다. –

+0

그것은 다른 Azure 광고에서 사용자 것 같습니다. 응용 프로그램을 만든 AD의 사용자 자격 증명을 사용하여 시도해 볼 수 있습니까? –

+0

예, 사용자가 모든 권한을 가진 디렉토리에 있습니다! –

관련 문제