private static TokenInfo GetNewToken(string oAuth2Url, string content) { HttpClient client = new HttpClient(); StringContent scontent = new StringContent(content); scontent.Headers.ContentType.MediaType = "application/x-www-form-urlencoded"; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; TokenDictionary.WriteLogMessage("Calling url:'" + oAuth2Url + "' to get a new token"); TokenInfo tokenInfo = null; try { var response = client.PostAsync(oAuth2Url, scontent).GetAwaiter().GetResult(); response.EnsureSuccessStatusCode(); string retval = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); if (response.Content.Headers.ContentType == null) { throw new InvalidDataException("OAuth2.0 endpoint did not return JSON format."); } else if (response.Content.Headers.ContentType.MediaType == "application/json") { tokenInfo = JsonConvert.DeserializeObject <TokenInfo>(retval); } else if (response.Content.Headers.ContentType.MediaType == "application/xml") { throw new InvalidDataException("OAuth2.0 endpoint returned XML format which is not supported."); } } catch (Exception ex) { WriteLogMessage(ex.Message, EventLogEntryType.Error); throw ex; } return(tokenInfo); }
public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel) { HttpRequestMessageProperty httpRequest = null; if (request.Properties.ContainsKey(HttpRequestMessageProperty.Name)) { httpRequest = request.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty; } if (httpRequest == null) { httpRequest = new HttpRequestMessageProperty() { Method = "GET", SuppressEntityBody = true }; request.Properties.Add(HttpRequestMessageProperty.Name, httpRequest); } WebHeaderCollection headers = httpRequest.Headers; string token = CacheToken ? AppDomainHelper.TokenDictionary.GetToken(OAuth2TokenEndPoint, ClientId, ClientSecret, Claims) : TokenDictionary.GetNewToken(OAuth2TokenEndPoint, ClientId, ClientSecret, Claims).Token; //Remove the authorization header if already exists. headers.Remove(HttpRequestHeader.Authorization); headers.Add(HttpRequestHeader.Authorization, "Bearer " + token); return(null); }
private static Lazy <TokenDictionary> CreateLazyWrapperOnDefaultAppDomain() { return(new Lazy <TokenDictionary>(() => { var wrapper = new TokenDictionary(); AppDomain.CurrentDomain.SetData(dicGuid, wrapper); return wrapper; })); }
private static Lazy <TokenDictionary> CreateLazyWrapperOnOtherDomain() { return(new Lazy <TokenDictionary>(() => { var defAppDomain = AppDomainHelper.DefaultAppDomain; TokenDictionary wrapper = (TokenDictionary)defAppDomain.GetData(dicGuid); if (wrapper == null) { defAppDomain.DoCallBack(CreateCallback); wrapper = (TokenDictionary)defAppDomain.GetData(dicGuid); } return wrapper; })); }