Tuesday 7 November 2017

ADAL .NET v3: Authenticate without popping up a login form

After successfully working with OrganizationService endpoint for CRM, performing the CRUD operations I decided to move to WEB API because it is the future.

During my learning process, I had issues

  1.  I wanted the silent login: a situation where I provide the user credentials directly in the code. The sample code on MSDN didn't provide that scenario. It always popped up the login form.
ADAL v2 had a UserCredential Class that takes 0 or 2 arguments (username, password), which allows us to pass the credentials without a pop-up login form.

ADAL v3 UserCredential Class now takes 0 or 1 argument(username) which makes the scenario a bit different. In case you are using ADAL v3, the UserPasswordCredential Class should be used: It takes the username and password.

ADAL v2

 var authContext = new AuthenticationContext(Authority);
 var userCredential = new UserCredential(username, password);
 string accesstoken = authContext.AcquireToken(ResourceUrl, ClientId, userCredential);
Instead use
ADAL v3
  var authContext = new AuthenticationContext(Authority);
 var userCredential = new UserPasswordCredential(username, password);
 string accesstoken = authContext.AcquireTokenAsync(ResourceUrl, ClientId, userCredential).Result;