0

OK, ASP.Net Core 2.0 API 용 VS2017에서 새 프로젝트를 만들고 있습니다. 나는 Azure AD를 설치하고 마법사에서 새 프로젝트를 설정하기 위해 Change Authentication (인증 변경)을 선택하고 "Work or School accont"라고 표시된 다음 Azure AD의 이름 (예 : mycompany.onmicrosoft.com)을 입력합니다. 프로젝트가 생성됩니다와 나는 Startup.csAzure AD를 Identity Provider로 사용하도록 ASP.Net Core 2.0 API를 구성하는 방법

public void ConfigureServices(IServiceCollection services) 
    { 
     services.AddAuthentication(sharedOptions => 
     { 
      sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; 
     }) 
     .AddAzureAdBearer(options => Configuration.Bind("AzureAd", options)); 

     services.AddMvc(); 
    } 

이 코드의 추가를 볼 수 있고 내가 TenentID이 디렉토리 인 appSettings.json 파일

"AzureAd": { 
    "Instance": "https://login.microsoftonline.com/", 
    "Domain": "mycompany.onmicrosoft.com", 
    "TenantId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", 
    "ClientId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" 
}, 

에 추가 설정을 볼 수 있습니다 Azure AD에 대한 ID는 이고 ClientID는 현재 Azure AD에 등록되어 있으므로 새로 작성된 API의 ApplicationID 값입니다.

이 모든 것이 의미가 있습니다.

하지만 VS2017에서 프로젝트를 실행 한 다음 https://localhost:44348/api/values 위치로 이동하면 401 Unauthorized가 발생합니다.

필자가 실망한 부분은 필자의 테스트 용으로 승인 된 클라이언트 응용 프로그램으로 식별하기 위해 Azure에 https://localhost:44348 브라우저 인스턴스를 등록해야합니다. 그러나 나는 그 일을 어디에서할지 명확하지 않습니다. Azure AD의 앱 등록에 https://localhost:44348을 등록해야합니까? Azure AD의 새로운 API 프로젝트에 대한 앱 등록에서 키를 생성하고 그 키를 인증 헤더의 비밀 키로 어떻게 든 전달해야합니까?

우편 배달부를 사용하여 이것을 테스트하려면 어떻게해야합니까? 내가 어떻게 그럴 수 있니? Azure 광고에 우편 배달부를 등록해야합니까?

많은 Google 페이지를 살펴 봤지만 웹 페이지에서 대화 형 로그인을 수행하고 Azure AD에 웹 페이지 로그인 URL을 등록하는 방법을 보여주는 많은 예제가 있지만 테스트를 시도 할 때 수행하는 방법은 아닙니다 VS2017 디버그 또는 Postman의 API

어떻게하면됩니까?

EDIT - 댓글을 읽은 다음 콘솔 응용 프로그램을 만들고 Azure AD 앱 등록에 등록하고 키를 만들었습니다. 나는이 프로세스 서버를 서버 OAUTH2 프로세스에 대해 이해하려고 시도 할 수있는 다른 모든 사람들을 위해 여기에 제공하고 있습니다.

this 아래의 코드 디자인에서 GitHub 레포에 대한 크레딧; 여기

콘솔 응용 프로그램 코드

using Microsoft.IdentityModel.Clients.ActiveDirectory; 
using System; 
using System.Configuration; 
using System.Globalization; 
using System.Net.Http; 
using System.Net.Http.Headers; 
using System.Threading; 
using System.Threading.Tasks; 
using System.Web.Script.Serialization; 

namespace API.TestConsole 
{ 
    class Program 
    { 

     /// <summary> 
     /// The AAD Instance is the instance of Azure. 
     /// </summary> 
     /// <remarks> 
     /// Example: https://login.microsoftonline.com/{0} 
     /// </remarks> 
     private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"]; 

     /// <summary> 
     // The Tenant is the Directory ID of the Azure AD tenant in which this application is registered. 
     /// </summary> 
     private static string tenant = ConfigurationManager.AppSettings["ida:Tenant"]; 

     /// <summary> 
     /// The Client ID is used by this application to uniquely identify itself to Azure AD. 
     /// </summary> 
     /// <remarks> 
     /// This value is obtained when this application is registered in Azure AD 
     /// </remarks> 
     private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"]; 

     /// <summary> 
     // The App Key is a credential used by this application to authenticate to Azure AD. 
     /// </summary> 
     /// <remarks> 
     /// This value is generated when this application is registered in Azure AD and assigned a key 
     /// </remarks> 
     private static string appKey = ConfigurationManager.AppSettings["ida:AppKey"]; 

     /// <summary> 
     // The Authority is the sign-in URL of the tenant. 
     /// </summary> 
     /// <remarks> 
     /// This is a string combination of the aadInstance and the tenant 
     /// </remarks> 
     static string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant); 

     /// <summary> 
     /// The ApplicationID of the evsApi service in Azure 
     /// </summary> 
     private static string apiResourceId = ConfigurationManager.AppSettings["api:ApiResourceId"]; 

     /// <summary> 
     /// The base URL address of the Api service 
     /// </summary> 
     private static string apiBaseAddress = ConfigurationManager.AppSettings["api:ApiBaseAddress"]; 


     private static HttpClient httpClient = new HttpClient(); 
     private static AuthenticationContext authContext = null; 
     private static ClientCredential clientCredential = null; 

     static void Main(string[] args) 
     { 

      // As a test, call the test Api, values endpoint 10 times with a short delay between calls 
      authContext = new AuthenticationContext(authority); 
      clientCredential = new ClientCredential(clientId, appKey); 

      for (int i = 0; i < 10; i++) 
      { 
       Thread.Sleep(3000); 
       GetValues().Wait(); 
      } 
      Console.WriteLine("Press ENTER to exit."); 
      Console.ReadLine(); 
     } 

     static async Task GetValues() 
     { 
      // Get an access token from Azure AD using client credentials. 
      // If the attempt to get a token fails because the server is unavailable, retry twice after 3 seconds each. 
      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(apiResourceId, clientCredential); 
       } 
       catch (AdalException ex) 
       { 
        if (ex.ErrorCode == "temporarily_unavailable") 
        { 
         retry = true; 
         retryCount++; 
         Thread.Sleep(3000); 
        } 

        Console.WriteLine(
         String.Format($"An error occurred while acquiring a token\nTime: " + 
         $"{DateTime.Now.ToString()}\nError: {ex.ToString()}\nRetry: {retry.ToString()}\n")); 
       } 

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

      if (result == null) 
      { 
       Console.WriteLine("Canceling attempt to contact the test API service.\n"); 
       return; 
      } 

      // Add the access token to the authorization header of the request. 
      httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); 

      // Call the values endpoint in the test API service. This is an HTTP GET. 
      Console.WriteLine("Retrieving values from Values endpoint at {0}", DateTime.Now.ToString()); 
      HttpResponseMessage response = await httpClient.GetAsync(apiBaseAddress + "/api/values"); 

      if (response.IsSuccessStatusCode) 
      { 
       // Read the response and output it to the console. 
       string s = await response.Content.ReadAsStringAsync(); 
       Console.WriteLine($"Values Result: {s}\n"); 
      } 
      else 
      { 
       Console.WriteLine("Failed to retrieve Values\nError: {0}\n", response.ReasonPhrase); 
      } 
     } 

    } 
} 

입니다 그리고 여기의 app.config

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
    <startup> 
     <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" /> 
    </startup> 
    <appSettings> 
    <add key="ida:AADInstance" value="https://login.microsoftonline.com/{0}" /> 

    <!-- This is the Directory ID value of the Azure AD --> 
    <add key="ida:Tenant" value="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" /> 

    <!-- This is the Application ID value of this test console application as it is 
     registered in the Azure AD app registration in the portal directory -->  
    <add key="ida:ClientId" value="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" /> 

    <!-- This is the Key value of this test console application, as it is 
     generated in the keys section for "Test Console Key" in the Azure AD app registration 
     for this test console application in the portal directory --> 
    <add key="ida:AppKey" value="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" /> 

    <!-- This is the Application ID value of the test api application as it is 
     registered in the Azure AD app registration in the portal directory --> 
    <add key="api:apiResourceId" value="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" /> 

    <!-- This is the custom domain URL assigned to the test app service in the Azure 
     portal --> 
    <add key="api:apiBaseAddress" value="https://testapi.mycompany.com" /> 
    </appSettings> 

</configuration> 
+0

간단히 말하면 액세스 토큰이 필요합니다. 액세스 토큰은 어떻게 구합니까? 클라이언트 자격 증명과 같은 인증 절차를 통해 https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-protocols-oauth-service-to-service. 또는 OpenID Connect를 사용해야 할 수도 있습니다. https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-protocols-openid-connect-code 클라이언트 자격 증명은 앱 호출로, OIDC는 사용자로 API 호출을 허용합니다. – juunas

+0

일부 권한을 추가하지 않으면 사용자로 전화해야합니다. https://joonasw.net/view/defining-permissions-and-roles-in-aad – juunas

+0

어쨌든, 전화를 걸 수있는 앱을 등록해야합니다 API를 사용하고 API에 대한 액세스 권한을 부여합니다. – juunas

답변

1

단순히 넣어, 당신은 액세스 토큰이 필요합니다.

어떻게 액세스 토큰을 얻습니까? OAuth 클라이언트 자격증 명과 같은 인증 과정을 통해 : https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-protocols-oauth-service-to-service.

또는 OpenID Connect : https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-protocols-openid-connect-code을 사용해야 할 수도 있습니다.

클라이언트 자격 증명은 앱으로 호출하며 OIDC (및 일부 다른 흐름)는 API로 사용자를 호출 할 수 있습니다.https://joonasw.net/view/defining-permissions-and-roles-in-aad

어쨌든, 당신은 API를 호출 응용 프로그램을 등록해야하며, 그것에게 API에 대한 액세스 권한을 부여 :

당신은 당신이 어떤 권한을 추가하지 않는 사용자로 전화를해야합니다.

관련 문제