Get Azure Active Directory Token with username and password
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);
}
}
Comments
-
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
andAcquireToken
, 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 over 7 yearsHave you tried to made the method
async
and putawait
in front ofauthContext.AcquireTokenAsync()
method call? -
Muhamed AlGhzawi over 7 yearsYes, and it takes forever with no response, i mentioned that in my question
-
Gaurav Mantri over 7 yearsCan you share the complete code (including method signature and how you're calling this method)?
-
Muhamed AlGhzawi over 7 yearsThe is shared above, This is just a test method
public AuthenticationResult getAccessToken() { }
-
Kanishk Panwar over 7 yearsWhat adal version are you using?
-
Muhamed AlGhzawi over 7 yearsIt's '2.18.206251556'
-
-
Gaurav Mantri over 7 years2 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 over 7 yearsExactly, 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 over 7 yearsI 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 over 7 yearsIt 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 over 7 yearsYes, the user is in the directory with full permissions!
-
Tony almost 7 yearsYes 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 almost 7 yearsalso not that UserCredential only access the username for now for security purposes.