/// <summary> /// Get the latest sales agent token given the AD Authorization Token /// </summary> /// <param name="adAuthorizationToken">AD Authorization Token</param> /// <param name="saAuthorizationToken">Sales agent authorization token, can be null</param> /// <returns>Latest sales agent token</returns> public static AuthorizationToken GetSA_Token(AuthorizationToken adAuthorizationToken, AuthorizationToken saAuthorizationToken = null) { if (saAuthorizationToken == null || (saAuthorizationToken != null && saAuthorizationToken.IsNearExpiry())) { //// Refresh the token on one of two conditions //// 1. If the token has never been retrieved //// 2. If the token is near expiry CSPTokenResponse saToken = GetSA_Token(adAuthorizationToken.AccessToken); saAuthorizationToken = new AuthorizationToken(saToken.access_token, Convert.ToInt64(saToken.expires_in)); } return(saAuthorizationToken); }
/// <summary> /// Given the ad token this method retrieves the sales agent token for accessing any of the partner apis /// </summary> /// <param name="adToken">this is the access_token we get from AD</param> /// <returns>the sales agent token object which contains access_token, expiration duration</returns> private static dynamic GetSA_Token(string adToken) { CSPTokenResponse result = null; var request = (HttpWebRequest)WebRequest.Create("https://api.cp.microsoft.com/my-org/tokens"); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.Accept = "application/json"; request.Headers.Add("api-version", "2015-03-31"); request.Headers.Add("x-ms-correlation-id", Guid.NewGuid().ToString()); request.Headers.Add("Authorization", "Bearer " + adToken); string content = "grant_type=client_credentials"; using (var writer = new StreamWriter(request.GetRequestStream())) { writer.Write(content); } try { Utilities.PrintWebRequest(request, content); var response = request.GetResponse(); using (var reader = new StreamReader(response.GetResponseStream())) { var responseContent = reader.ReadToEnd(); Utilities.PrintWebResponse((HttpWebResponse)response, responseContent); result = JsonConvert.DeserializeObject <CSPTokenResponse>(responseContent); } } catch (WebException webException) { using (var reader = new StreamReader(webException.Response.GetResponseStream())) { var responseContent = reader.ReadToEnd(); Utilities.PrintErrorResponse((HttpWebResponse)webException.Response, responseContent); } } return(result); }