Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Azure Active Directory Token with username and password

I'm trying to authenticate my client using AAD and automate this using a Windows Service. In AAD .NET SDK, There's two methods, AcquireTokenAsync and AcquireToken, but i can't use either of these methods, the await call will stay forever with no response, and when i do something like this:

result = authContext.AcquireTokenAsync(resourceHostUri, clientId, new UserCredential(hardcodedUsername, hardcodedPassword)).Result;

The object returns a status of Waiting for Activation & Code 31..

Now, Is there anyway to acquire the token using hardcoded username and password?

My full code:

        string hardcodedUsername = "username";
        string hardcodedPassword = "password";

        string tenant = "[email protected]";
        string clientId = "clientId";
        string resourceHostUri = "https://management.azure.com/";
        string aadInstance = "https://login.microsoftonline.com/{0}";

        string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);


        authContext = new AuthenticationContext(authority);

        AuthenticationResult result = null;
            try
            {

                result = authContext.AcquireTokenAsync(resourceHostUri, clientId, new UserCredential(hardcodedUsername, hardcodedPassword)).Result;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }

            return result;

I'm trying to get access to Azure API.

UPDATE 1:

I got this in the output when i tried to await the call, i think this might help:

Microsoft.IdentityModel.Clients.ActiveDirectory TokenCache: Looking up cache for a token... Microsoft.IdentityModel.Clients.ActiveDirectory TokenCache: No matching token was found in the cache Microsoft.IdentityModel.Clients.ActiveDirectory d__0: Sending user realm discovery request to 'https://login.microsoftonline.com/common/UserRealm/username?api-version=1.0' Microsoft.IdentityModel.Clients.ActiveDirectory d__4: User with hash '***' detected as 'Federated'

like image 329
Muhamed AlGhzawi Avatar asked Aug 17 '16 09:08

Muhamed AlGhzawi


1 Answers

try below link code

https://msdn.microsoft.com/en-in/library/partnercenter/dn974935.aspx

how to get access token after windows azure active directory authentication

How to get current token from Azure ActiveDirectory application

// Get OAuth token using client credentials 
string tenantName = "GraphDir1.OnMicrosoft.com";
string authString = "https://login.microsoftonline.com/" + tenantName;

AuthenticationContext authenticationContext = new AuthenticationContext(authString, false);

// Config for OAuth client credentials  
string clientId = "118473c2-7619-46e3-a8e4-6da8d5f56e12";
string key = "hOrJ0r0TZ4GQ3obp+vk3FZ7JBVP+TX353kNo6QwNq7Q=";
ClientCredential clientCred = new ClientCredential(clientId, key);
string resource = "https://graph.windows.net";
string token;
try
{
    AuthenticationResult authenticationResult = authenticationContext.AcquireToken(resource, clientCred);
    token = authenticationResult.AccessToken;
}
catch (AuthenticationException ex)
{
    Console.ForegroundColor = ConsoleColor.Red;
    Console.WriteLine("Acquiring a token failed with the following error: {0}", ex.Message);
    if (ex.InnerException != null)
    {
        //  You should implement retry and back-off logic according to
        //  http://msdn.microsoft.com/en-us/library/dn168916.aspx . This topic also
                                //  explains the HTTP error status code in the InnerException message. 
        Console.WriteLine("Error detail: {0}", ex.InnerException.Message);
    }
}
like image 189
Nik Varma Avatar answered Oct 23 '22 16:10

Nik Varma