2

API 응용 프로그램에 액세스하려고합니다. Azure에서 호스팅되고 Azure AD로 보안되었습니다.Azure AD 베어러 토큰을 사용하여 API App에 대해 웹 응용 프로그램 인증

API 앱의 경우 App Service Authentication = Azure Active Directory "Express"관리 모드를 설정했습니다.

"클래식"포털에서는 광고 아래에 몇 가지 응용 프로그램을 만들었습니다. 하나는 API App 용이고 다른 하나는 Web App 용입니다. 그리고 Web App의 경우 "다른 응용 프로그램에 대한 사용 권한"아래에 API 응용 프로그램에 대한 항목을 추가했습니다 (그러나 "응용 프로그램에 액세스하는 데 필요한 사용자 할당"이 API 응용 프로그램에 대해 필요하지는 않습니다.). 또한 웹 응용 프로그램의 키를 생성했습니다. 여기에 주어진 예제 코드에 따라

- 나는 성공적으로 다음 코드를 사용하여 토큰 베어러를 얻을 수 있습니다

https://github.com/Azure-Samples/active-directory-dotnet-webapp-webapi-oauth2-appidentity ... :

private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"]; 
private static string tenant = ConfigurationManager.AppSettings["ida:Tenant"]; 
private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"]; 
private static string appKey = ConfigurationManager.AppSettings["ida:AppKey"]; 

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

private static string ApiId = ConfigurationManager.AppSettings["ApiId"]; 

private static AuthenticationContext authContext = new AuthenticationContext(authority); 
private static ClientCredential clientCredential = new ClientCredential(clientId, appKey); 

을 ...

AuthenticationResult result = null; 
int retryCount = 0; 
bool retry = false; 

do 
{ 
    retry = false; 
    try 
    { 
     // ADAL includes an in memory cache, so this call will only send a message to the server if the cached token is expired. 
     result = await authContext.AcquireTokenAsync(ApiId, clientCredential); 
    } 
    catch (AdalException ex) 
    { 
     if (ex.ErrorCode == "temporarily_unavailable") 
     { 
      retry = true; 
      retryCount++; 
      Thread.Sleep(3000); 
     } 
    } 

} while ((retry == true) && (retryCount < 3)); 

if (result == null) 
    return Request.CreateResponse(HttpStatusCode.InternalServerError, "Could not authenticate against API."); 

그러나 때 웹 응용 프로그램에서 API 응용 프로그램에 대한 요청과 함께 무기명 토큰을 사용합니다. 나는 항상 401 인증되지 않은 응답을받습니다 :

StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: 
{ 
    Date: Wed, 13 Jul 2016 08:43:09 GMT 
    Server: Microsoft-IIS/8.0 
    WWW-Authenticate: Bearer realm="MY-API-APP-ID-IS-HERE" 
    X-Powered-By: ASP.NET 
    Content-Length: 58 
    Content-Type: text/html 
} 

이것은 내가 함께 실패 년대 요청을 만들기 위해 사용하고 코드는 401 :

var apiUri = new Uri(ConfigurationManager.AppSettings["ApiUrl"] + "/api/MethodImCalling"); 
var client = new RestClient(apiUri.GetLeftPart(UriPartial.Authority)); 
var request = new RestRequest(apiUri, Method.GET); 
request.AddHeader("Authorization", "Bearer " + result.AccessToken); 
request.AddParameter("something", somevalue); 
var response = client.Execute(request); 

if (response.StatusCode != HttpStatusCode.OK) 
    return Request.CreateResponse(response.StatusCode); // Relay non-successful response 

내가 잘못하고있을 수도 있고 놓친 거지 무엇을 어떤 아이디어가? 미리 감사드립니다!

Log App을 Azure에 이미 문제없이 API 응용 프로그램에 액세스하고 있지만 논리 응용 프로그램 json의 인증 자격 증명에 "잠재 고객"매개 변수가 포함되어 있습니다. 위의 코드는 "잠재 고객"을 사용하지 않으므로 퍼즐의 누락 부분이 될 수 있으며, 그렇다면 어떻게 추가합니까?

웹 응용 프로그램이 API 응용 프로그램에 액세스 할 수 있도록 구성되었습니다 방법을 보여주는

스크린 샷 : enter image description here

+1

당신은 또한 당신이 권한에 대한 API를 구성한 방법에 대한 세부 사항을 공유 할 수 있습니다

현재이 두 가지 방법에 대한 자세한 정보를 찾을 수 있습니까? –

+0

@PhilippeSignoret - App Service Authenication = Azure Active Directory "익스프레스"관리 모드를 사용 중입니다 (질문에 추가됩니다). 이게 너가하는 세부 사항이야? 확실하지 다른 세부 사항을 제공합니다. 건배. – Gavin

+0

Azure에 배포하기 전에 로컬에서 샘플 코드가 제대로 작동합니까?액세스 토큰으로 API에 액세스 할 수 없으면 JWT 디코딩 도구를 사용하여 토큰을 분석하는 것이 좋습니다. 여기에 JWT 디코딩 된 웹 페이지가 있습니다 : https://jwt.io/. –

답변

2

이유는 401 응답을 받고 당신이 단지 응용 프로그램 위임 된 권한을 허용 한, 그러나 당신은을 사용하는 것입니다 응용 프로그램 권한이 필요한 클라이언트 자격 증명 플로.

인증 코드 흐름을 사용하도록 코드를 변경하거나 웹 응용 프로그램의 응용 프로그램 권한을 웹 API에 부여 할 수 있습니다.

인증 코드 흐름을 사용하려면 대신 AcquireTokenByAuthorizationCodeAsync를 사용하도록 코드를 변경해야합니다. https://azure.microsoft.com/en-us/documentation/articles/active-directory-authentication-scenarios/#web-application-to-web-api

+0

포인터 사카 주셔서 감사합니다. 나는 당신이 지시 한 것을 기반으로 솔루션을 구현하려고합니다. 내 머리를 감싸는 데 약간의 학습 곡선이 필요합니다. 일단 그것을 알아 낸 후에는 대답으로 표시 할 것입니다. Microsoft에서 탐색 할 몇 가지 코드 예제를 찾았습니다.하지만 웹 응용 프로그램의 권한을 웹 API에 부여하려고합니다. – Gavin

+0

나는 이것으로 정말로 고심하고있다. 간단 할 수도 있지만 "웹 앱에서 웹 API로 애플리케이션 권한을 부여하는 부분"은 무엇입니까? – Gavin

+0

내 문제는 다음과 같을 수 있습니다. http://stackoverflow.com/questions/38262085/azure-ad-ap-request-401-unauthorized 및 http://stackoverflow.com/questions/37404286/azure- ad-http-1-1-401-unauthorized-windows-service – Gavin

관련 문제