Youness Abbassi Youness Abbassi - 8 days ago 10
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

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 = "yourDirectory.onmicrosoft.com";
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("https://login.windows.net/" + directoryName);
var result = await authenticationContext.AcquireTokenAsync("https://management.core.windows.net/", 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

Comments