ADAL v3: How to authenticate using UserPasswordCredential?

Trondh picture Trondh · Nov 9, 2016 · Viewed 7.7k times · Source

ADAL v3 has the UserPasswordCredential class, but I cannot find a working implementation. There's no AcquireToken overload which accepts a UserPasswordCredential or UserCredential type. What is the correct way of performing the username&password flow in ADAL v3? This particular piece of code is using full .Net 4.5.

Answer

Fei Xue - MSFT picture Fei Xue - MSFT · Nov 9, 2016

If you were developing with client app, you can refer the code below to acquire the token:

string authority = "https://login.microsoftonline.com/xxxx.onmicrosoft.com";
string resrouce = "https://graph.windows.net";
string clientId = "";
string userName = "";
string password = "";
UserPasswordCredential userPasswordCredential = new UserPasswordCredential(userName,password);
AuthenticationContext authContext = new AuthenticationContext(authority);
var token= authContext.AcquireTokenAsync(resrouce,clientId, userPasswordCredential).Result.AccessToken;

And if you were developing with web app( this is not common scenario), there is no such method in ADAL V3 to support this scenario. As a workaround, you may construct the request yourself. Here is an example for your reference:

POST: https://login.microsoftonline.com/xxxxx.onmicrosoft.com/oauth2/token

Content-Type: application/x-www-form-urlencoded
resource={resource}&client_id={clientId}&grant_type=password&username={userName}&password={password}&scope=openid&client_secret={clientSecret}