5
votes

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'

2
Have you tried to made the method async and put await in front of authContext.AcquireTokenAsync() method call?Gaurav Mantri
Yes, and it takes forever with no response, i mentioned that in my questionMuhamed AlGhzawi
Can you share the complete code (including method signature and how you're calling this method)?Gaurav Mantri
The is shared above, This is just a test method public AuthenticationResult getAccessToken() { }Muhamed AlGhzawi
What adal version are you using?Kanishk Panwar

2 Answers

0
votes

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);
    }
}
0
votes

Please try the following:

    static void Main(string[] args)
    {
        Task<AuthenticationResult> t = getAccessToken();
        t.Wait();
        var result = t.Result;
        Console.WriteLine(result.AccessToken);
        Console.WriteLine("Please any key to terminate the program");
        Console.ReadKey();
    }

    public static async Task<AuthenticationResult> getAccessToken()
    {
        string hardcodedUsername = "username";
        string hardcodedPassword = "password";

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

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


        var authContext = new AuthenticationContext(authority);

        AuthenticationResult result = null;
        try
        {
            result = await authContext.AcquireTokenAsync(resourceHostUri, clientId, new UserCredential(hardcodedUsername, hardcodedPassword));
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.StackTrace);
            System.Diagnostics.Debug.WriteLine(ex.Message);
        }

        return result;
    }

What I have done is made getAccessToken() method async and inside that the code is made to wait to get the token when you call authContext.AcquireTokenAsync.