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をアイデンティティプロバイダとして使用するための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を取得しています。

私は、私のテストのための承認されたクライアントアプリケーションとしてそれを識別するために私のhttps://localhost:44348ブラウザインスタンスを何らかの形でAzureに登録しなければならないことが分かっています。しかし、私はそれをどこで行うべきか明確ではない。 Azure ADのアプリケーション登録でhttps://localhost:44348を登録するだけですか?Azure ADの新しいAPIプロジェクトのアプリ登録でキーを生成し、そのキーを私の認証ヘッダーの秘密として何らかの形で渡すはずですか?

郵便配達員を使用してこれをテストしたい場合はどうすればよいですか?どうすればいい? Azure ADに郵便配達員を登録しなければなりませんか?

私は多くのGoogleページを見てきましたが、Webページからインタラクティブなログインを行い、そのWebページのサインインURLをAzure ADに登録する方法を示す例がたくさんありますが、 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へのアクセス権を与える:

あなたは、いくつかの権限を追加しない限り、ユーザーとして呼び出す必要があります。

関連する問題