public bool Authenticate(HttpRequestMessage request) { if (m_authFlow != AuthFlow.Obtained) { var host = GetHost(request.RequestUri.AbsoluteUri); var authUriString = $"{host}/oauth2/token"; HttpClient authClient = new HttpClient(); HttpRequestMessage authReq = new HttpRequestMessage() { RequestUri = new Uri(authUriString), Method = HttpMethod.Post }; authReq.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); authReq.Headers.Add("ContentType", "application/x-www-form-urlencoded"); List <KeyValuePair <string, string> > authReqContent; switch (m_authFlow) { case AuthFlow.ObtainAccessTokenPending: authReqContent = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("grant_type", "client_credentials"), new KeyValuePair <string, string>("client_id", m_ClientId), new KeyValuePair <string, string>("client_secret", m_ClientSecret) }; break; case AuthFlow.RefreshAccessTokenPending: if (m_authData == null) { throw new Exception($"Wrong OAuth2 flow"); } authReqContent = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("grant_type", "refresh_token"), new KeyValuePair <string, string>("refresh_token", m_authData.RefreshToken) }; break; default: throw new Exception($"Wrong OAuth2 flow"); } authReq.Content = new FormUrlEncodedContent(authReqContent); var authResponse = authClient.SendAsync(authReq).Result; if (authResponse.StatusCode == System.Net.HttpStatusCode.OK) { var content = authResponse.Content.ReadAsStringAsync().Result; m_authData = OAuthData.Deserialize(content); m_authFlow = AuthFlow.Obtained; } } if (m_authData != null) { if (m_authData.HasError) { throw new Exception($"OAuth 2.0: Authentication error: {m_authData.Error}", new Exception(m_authData.ErrorDescription)); } request.Headers.Add("Authorization", AuthorizationHeaderValue); } return(true); }
protected override void AuthDataDeserializeImpl(string content) { m_authData = OAuthData.Deserialize(content); }