0

How do I authenticate a user against Azure active Directory in my console application without redirecting to the login page?

string tenantName = "---";
string authString = "https://login.microsoftonline.com/" + tenantName;
AuthenticationContext authenticationContext = new AuthenticationContext(authString, false);
// Config for OAuth client credentials  
string clientId = "---";
string key = "---";
ClientCredential clientCred = new ClientCredential(clientId, key);
string resource = "https://pwsintsnapitazure.azurewebsites.net";
string token;
AuthenticationResult authenticationResult = authenticationContext.AcquireTokenAsync(resource, clientCred).Result;
token = authenticationResult.AccessToken;
swatsonpicken
  • 873
  • 1
  • 7
  • 21
ravi rathod
  • 461
  • 1
  • 4
  • 6
  • when i tried this above sample code i got error "ex = {"AADSTS70002: The request body must contain the following parameter: 'client_secret or client_assertion" – ravi rathod Aug 10 '17 at 06:15
  • Your code is using client credential flow . Please click [here](http://www.cloudidentity.com/blog/2014/07/08/using-adal-net-to-authenticate-users-via-usernamepassword/) and [here](https://blogs.msdn.microsoft.com/wushuai/2016/09/25/resource-owner-password-credentials-grant-in-azure-ad-oauth/) for how to authenticate users via Username/Password . [Here](https://github.com/Azure-Samples/active-directory-dotnet-native-headless) is a code sample . – Nan Yu Aug 10 '17 at 06:22
  • RequestMessage = {Method: POST, RequestUri: 'https://login.microsoftonline.com/142d56e1-4ab5-4f5d-8140-d3db9fbf4cac/oauth2/token?', Version: 1.1, Content: System.Net.Http.StringContent, Headers: { Accept: application/x-www-form-urlencoded Content-Type: application/x-... – ravi rathod Aug 10 '17 at 07:11
  • See my reply in your new thread :https://stackoverflow.com/questions/45609432/ex-aadsts70002-the-request-body-must-contain-the-following-parameter-clie/45630699#45630699 – Nan Yu Aug 11 '17 at 08:44

1 Answers1

0

With your code (authenticationContext.AcquireTokenAsync(resource, clientCred)) to acquire token is performing the client credential flow . With this flow, the application presents its client credentials to the OAuth2 token issuing endpoint, and in return gets an access token that represents the application itself without any user information .

If you want to authenticate a user against Azure active Directory and not show the login page , you could use Resource owner flow , please click here and here for how to authenticate users via Username/Password . Please pay attention to Constraints & Limitations section in first link .

Nan Yu
  • 26,101
  • 9
  • 68
  • 148