/// <summary> /// Get the latest AD token given the reseller domain and client credentials /// </summary> /// <param name="domain">domain of the reseller</param> /// <param name="clientId">clientID of the application</param> /// <param name="clientSecret">client secret of the application, also refered to as key</param> /// <returns>Latest AD Authorization token</returns> public static AuthorizationToken GetAD_Token(string domain, string clientId, string clientSecret) { AzureTokenResponse adToken = GetADToken(domain, clientId, clientSecret); AuthorizationToken adAuthorizationToken = new AuthorizationToken(adToken.access_token, Convert.ToInt64(adToken.expires_in)); return(adAuthorizationToken); }
/// <summary> /// Given the reseller domain, clientid and clientsecret of the app, this method helps to retrieve the AD token /// </summary> /// <param name="resellerDomain">domain of the reseller including .onmicrosoft.com</param> /// <param name="clientId">AppId from the azure portal registered for this app</param> /// <param name="clientSecret">Secret from the azure portal registered for this app</param> /// <returns>this is the authentication token object that contains access_token, expiration time, can be used to get the authorization token from a resource</returns> private static AzureTokenResponse GetADToken(string resellerDomain, string clientId, string clientSecret) { AzureTokenResponse result = null; var request = WebRequest.Create(string.Format("https://login.microsoftonline.com/{0}/oauth2/token", resellerDomain)); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; string content = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&resource={2}", clientId, WebUtility.UrlEncode(clientSecret), WebUtility.UrlEncode("https://graph.windows.net")); using (var writer = new StreamWriter(request.GetRequestStream())) { writer.Write(content); } try { //Utilities.PrintWebRequest((HttpWebRequest)request, content); var response = request.GetResponse(); using (var reader = new StreamReader(response.GetResponseStream())) { var responseContent = reader.ReadToEnd(); //Utilities.PrintWebResponse((HttpWebResponse)response, "<snipped>"); result = JsonConvert.DeserializeObject <AzureTokenResponse>(responseContent); } } catch (WebException webException) { if (webException.Response != null) { using (var reader = new StreamReader(webException.Response.GetResponseStream())) { var responseContent = reader.ReadToEnd(); Utilities.PrintErrorResponse((HttpWebResponse)webException.Response, responseContent); } } } return(result); }