Youness Abbassi Youness Abbassi - 1 year ago 260
C# Question

C# Connect to Azure AD using username/password

I have an Azure Api REST which can be reach by entering a username/password .
how can i get access to this API from C# ?

after a little search , i found somthing about using AuthenticationContext .. but it couldn't work for me Authenticationcontext .AcquireToken(resource, clientId, credential);

where can i get the 'resource' parameter and the ClientID .

Thanks a lot

Answer Source

I based most of my work on this post that laid some groundwork.

You need to create a Native Application in your Azure AD first and add the Windows Azure Service Management API permission.

Creating AD App

The ClientID is obtained from this App.

This is the code I'm currently using to obtain a Token that can be used with the Management SDK:

string userName = "yourUserName";
string password = "yourPassword";
string directoryName = "";
string clientId = "{ClientId obtained by creating an App in the Active Directory}";
var credentials= new UserPasswordCredential(string.Format("{0}@{1}", userName, directoryName), password);
var authenticationContext = new AuthenticationContext("" + directoryName);
var result = await authenticationContext.AcquireTokenAsync("", clientID, credentials);
var jwtToken = result.AccessToken;
//Example accesing Azure Cdn Management API
string subscriptionId = "xxxx-xxxxxx-xxxx-xxxxxxx";
using (var cdn = new CdnManagementClient(new TokenCredentials(jwtToken)) { SubscriptionId = subscriptionId })
    //do something...

Your directory name can be obtained in the Azure Portal > Azure AD section, on Domain names.

Domain name

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download