通过 Azure Active Directory 对客户端进行身份验证以连接到 ApiApp

Authenticate client via Azure Active Directory to connect to ApiApp

我使用 Azure Active Directory 保护我的 Azure API 应用程序。

如何验证我的 C# .NET 客户端以便我可以调用 Api?我找不到任何这方面的教程!

https://aka.ms/aaddev中有很多全面的文档和示例,你应该花些时间去那里看看。我下面的回复都来自这些示例,特别是这个:

https://github.com/Azure-Samples/active-directory-dotnet-native-desktop

首先,您需要按照以下步骤在 Azure Active Directory 中注册您的客户端应用程序:

  1. Sign in to the Azure management portal.
  2. Click on Active Directory in the left hand nav.
  3. Click the directory tenant where you wish to register the sample application.
  4. Click the Applications tab.
  5. In the drawer, click Add.
  6. Click "Add an application my organization is developing".
  7. Enter a friendly name for the application, i.e. "YourClientApp", select "Native Client Application", and click next.
  8. Enter a Redirect URI, i.e. "https://yourClientsRedirectUri/". Click finish.
  9. Click the Configure tab of the application.
  10. Find the Client ID value and copy it aside, you will need this later when configuring your application.
  11. In "Permissions to Other Applications", click "Add Application." Select "Other" in the "Show" dropdown, and click the upper check mark. Locate & click on "YourApi", and click the bottom check mark to add the application. Select "Access YourApi" from the "Delegated Permissions" drop down, and save the configuration.

然后,对于 C# .NET 客户端,您需要使用适用于 .Net 的 Active Directory 身份验证库 (ADAL) 并执行以下操作:

var authority = "https://login.microsoftonline.com/";
var resource = "https://yourApisUri/";
var redirectUri = "https://yourClientsRedirectUri/";

var tenant = "yourAzureActiveDirectory.onmicrosoft.com";
var clientId = "yourClientsAzureADClientId";

var ctx = new AuthenticationContext(authority + tenant);

var t = ctx.AcquireToken(resource, clientId, new Uri(redirectUri));

using (var client = new HttpClient())
{
    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + t.AccessToken);

    var url = "https://yourapi.com/yourmethod";
    await result = client.GetAsync(url);

    // Do whatever you want
}

重要说明:上面的代码只是一个起点,您应该确保阅读并遵循所有最佳实践,例如确保将 TokenCache 传递给 AuthenticationContext 构造函数并确保每次需要令牌时调用 AcquireToken,而不是自己缓存令牌。