3
votes

I secured my Azure API App with Azure Active Directory.

How to authenticate my C# .NET client so I can call the Api? I can't find any tutorials on this!

1
which sort of client?Ivan G.

1 Answers

3
votes

There's lots of comprehensive documentation and samples in https://aka.ms/aaddev, you should spend some time poking around there. My response below all comes from those samples, specifically this one:

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

First off, you'll need to register you client app in Azure Active Directory by following these steps :

  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.

Then, for a C# .NET client, you'll need to use the Active Directory Authentication Library (ADAL) for .Net and do something along the lines of:

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
}

IMPORTANT NOTE: The code above is just a starting point, you should make sure you read and follow all the best practices such as ensuring you pass a TokenCache to the AuthenticationContext constructor and making sure you call AcquireToken every time you need a token and not caching the token yourself.