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!
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 :
- Sign in to the Azure management portal.
- Click on Active Directory in the left hand nav.
- Click the directory tenant where you wish to register the sample application.
- Click the Applications tab.
- In the drawer, click Add.
- Click "Add an application my organization is developing".
- Enter a friendly name for the application, i.e. "YourClientApp", select "Native Client Application", and click next.
- Enter a Redirect URI, i.e. "https://yourClientsRedirectUri/". Click finish.
- Click the Configure tab of the application.
- Find the Client ID value and copy it aside, you will need this later when configuring your application.
- 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.