Get Azure Active Directory Token with username and password

15,675

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);
    }
}
Share:
15,675
Muhamed AlGhzawi
Author by

Muhamed AlGhzawi

Just another passionate Windows developer :-)

Updated on June 09, 2022

Comments

  • Muhamed AlGhzawi
    Muhamed AlGhzawi almost 2 years

    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'

    • Gaurav Mantri
      Gaurav Mantri over 7 years
      Have you tried to made the method async and put await in front of authContext.AcquireTokenAsync() method call?
    • Muhamed AlGhzawi
      Muhamed AlGhzawi over 7 years
      Yes, and it takes forever with no response, i mentioned that in my question
    • Gaurav Mantri
      Gaurav Mantri over 7 years
      Can you share the complete code (including method signature and how you're calling this method)?
    • Muhamed AlGhzawi
      Muhamed AlGhzawi over 7 years
      The is shared above, This is just a test method public AuthenticationResult getAccessToken() { }
    • Kanishk Panwar
      Kanishk Panwar over 7 years
      What adal version are you using?
    • Muhamed AlGhzawi
      Muhamed AlGhzawi over 7 years
      It's '2.18.206251556'
  • Gaurav Mantri
    Gaurav Mantri over 7 years
    2 things: 1) OP wants to fetch the credentials using username/password combination and not by using client credentials and 2) OP is using async methods. What you've shown is sync method and you're using client credentials.
  • Muhamed AlGhzawi
    Muhamed AlGhzawi over 7 years
    Exactly, as my app in AAD is a Native Client, i can't get a key to do this kind of auth, what i need is to use my credentials (Username and Password)
  • Muhamed AlGhzawi
    Muhamed AlGhzawi over 7 years
    I tried that before, waiting with no any response, but this time i checked the output, there's something interesting.. i edited my question so you can see the output..
  • Gaurav Mantri
    Gaurav Mantri over 7 years
    It looks like the user is from other Azure AD. Can you try by using credentials of a user in the AD where you created the application?
  • Muhamed AlGhzawi
    Muhamed AlGhzawi over 7 years
    Yes, the user is in the directory with full permissions!
  • Tony
    Tony almost 7 years
    Yes I got this code working with a TOKEN response! So delete the AWAIT in this code: result = await authContext.AcquireTokenAsync(resourceHostUri, clientId, new UserCredential(hardcodedUsername, hardcodedPassword)); then delete t.wait() from the calling code, and walla!
  • Tony
    Tony almost 7 years
    also not that UserCredential only access the username for now for security purposes.