Skip to content

Instantly share code, notes, and snippets.

@jpda
Created June 9, 2017 19:44
Show Gist options
  • Select an option

  • Save jpda/97d9d56acf9d30323024aa138908e9d0 to your computer and use it in GitHub Desktop.

Select an option

Save jpda/97d9d56acf9d30323024aa138908e9d0 to your computer and use it in GitHub Desktop.
Azure AD Password grant type
private static string GetUserToken()
{
var cid = "<application client ID>";
var targetCid = "<target resource ID - be careful here, some apps require client/resource ID (GUID), others also accept a URI";
var key = "<URL-encoded client secret key>";
var reqUri = "<authority, usually something like https://login.microsoftonline.com/<tenant ID or domain name>/oauth2/token";
var postData = $"resource={targetCid}&client_id={cid}&grant_type=password&username=user%40jpda.onmicrosoft.com&password={password}&type=openid&client_secret={key}";
// example: "resource=00000002-0000-0000-c000-000000000000&client_id=eeb7d568-2e05-45cf-87eb-d07604340af7&grant_type=password&username=user%40jpda.onmicrosoft.com&password=lol&scope=openid&client_secret=urlencodedsecretkey"
var wc = new WebClient();
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
try
{
var response = wc.UploadString(reqUri, "POST", postData);
var tokenData = JObject.Parse(response);
var ats = tokenData["access_token"].Value<string>();
return ats;
}
catch (WebException ex)
{
using (var stream = ex.Response.GetResponseStream())
{
var reader = new StreamReader(stream);
Console.WriteLine(reader.ReadToEnd());
}
}
return string.Empty;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment