/// <summary> /// Unconditionally adds the authorization header to the request /// </summary> /// <param name="request">The request to add the authorization header to</param> /// <param name="header">The type of the HTTP header that stores the authorization information</param> /// <param name="authValue">The authentication header value</param> public static void SetAuthorizationHeader([NotNull] this IHttpRequestMessage request, AuthHeader header, [NotNull] string authValue) { var headerName = header.ToAuthorizationHeaderName(); request.Headers.Remove(headerName); request.Headers.Add(headerName, authValue); }
/// <summary> /// Asynchronously send a request /// </summary> /// <param name="request">The request do send</param> /// <param name="cancellationToken">The cancellation token used to signal an abortion</param> /// <returns>The task to query the response</returns> public async Task <IHttpResponseMessage> SendAsync(IHttpRequestMessage request, CancellationToken cancellationToken) { var requestMessage = request.AsHttpRequestMessage(); var response = await Client.SendAsync(requestMessage, cancellationToken); return(new DefaultHttpResponseMessage(requestMessage, response)); }
/// <summary> /// Initializes a new instance of the <see cref="DefaultHttpResponseMessage"/> class. /// </summary> /// <param name="requestMessage">The request message for this response</param> /// <param name="responseMessage">The response message to wrap</param> /// <param name="cookies">Container of cookies to query the cookies from</param> /// <param name="exception">The exception that occurred during the request</param> public DefaultHttpResponseMessage([NotNull] IHttpRequestMessage requestMessage, [CanBeNull] HttpWebResponse responseMessage, [CanBeNull] CookieContainer cookies, [CanBeNull] WebException exception = null) { ResponseMessage = responseMessage; _exception = exception; _requestMessage = requestMessage; var responseHeaders = new GenericHttpHeaders(); var contentHeaders = new GenericHttpHeaders(); if (responseMessage != null && responseMessage.HasHeaderSupport()) { foreach (var headerName in responseMessage.Headers.AllKeys) { IHttpHeaders headers; if (headerName.StartsWith("Content-", StringComparison.OrdinalIgnoreCase)) { headers = contentHeaders; } else { headers = responseHeaders; } headers.TryAddWithoutValidation(headerName, responseMessage.Headers[headerName]); } } Content = new HttpWebResponseContent(contentHeaders, responseMessage); Headers = responseHeaders; Cookies = cookies; }
public async Task <IHttpResponseMessage> SendAsync(IHttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken) { var message = ((HttpRequestMessage)request).Message; var response = await client.SendAsync(message, (Http.HttpCompletionOption) completionOption, cancellationToken); return(new HttpResponseMessage(response)); }
/// <summary> /// Determines if the authentication module can handle the challenge sent with the response. /// </summary> /// <param name="client">The REST client the response is assigned to</param> /// <param name="request">The REST request the response is assigned to</param> /// <param name="credentials">The credentials to be used for the authentication</param> /// <param name="response">The response that returned the authentication challenge</param> /// <returns>true when the authenticator can handle the sent challenge</returns> public virtual bool CanHandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response) { // No credentials defined? if (credentials == null) { return(false); } // No challenge header found? var authModeInfo = response.GetAuthenticationMethodValue(_authHeader, AuthenticationMethod); if (authModeInfo == null) { return(false); } // Search for credential for request URI var responseUri = client.GetRequestUri(request, response); var credential = credentials.GetCredential(responseUri, AuthenticationMethod); if (credential == null) { return(false); } // Did we already try to use the found credentials? if (ReferenceEquals(credential, _authCredential)) { // Yes, so we don't retry the authentication. return(false); } return(true); }
/// <summary> /// Initializes a new instance of the <see cref="DefaultHttpResponseMessage"/> class. /// </summary> /// <param name="requestMessage">The request message for this response</param> /// <param name="responseMessage">The response message to wrap</param> /// <param name="exception">The exception that occurred during the request</param> public DefaultHttpResponseMessage([NotNull] IHttpRequestMessage requestMessage, [NotNull] HttpWebResponse responseMessage, [CanBeNull] WebException exception = null) { ResponseMessage = responseMessage; _exception = exception; _requestMessage = requestMessage; var responseHeaders = new GenericHttpHeaders(); var contentHeaders = new GenericHttpHeaders(); if (responseMessage.SupportsHeaders) { foreach (var headerName in responseMessage.Headers.AllKeys) { IHttpHeaders headers; if (headerName.StartsWith("Content-", StringComparison.OrdinalIgnoreCase)) { headers = contentHeaders; } else { headers = responseHeaders; } headers.TryAddWithoutValidation(headerName, responseMessage.Headers[headerName]); } } _content = new HttpWebResponseContent(contentHeaders, responseMessage); _responseHttpHeaders = responseHeaders; }
/// <summary> /// Modifies the request to ensure that the authentication requirements are met. /// </summary> /// <param name="client">Client executing this request</param> /// <param name="request">Request to authenticate</param> /// <param name="credentials">The credentials used for the authentication</param> /// <returns>The task the authentication is performed on</returns> public async Task PreAuthenticate(IHttpClient client, IHttpRequestMessage request, ICredentials credentials) { foreach (var authenticator in _authenticators.Values.Select(x => x.Authenticator).Where(x => x.CanPreAuthenticate(client, request, credentials))) { await authenticator.PreAuthenticate(client, request, credentials).ConfigureAwait(false); } }
/// <summary> /// Modifies the request to ensure that the authentication requirements are met. /// </summary> /// <param name="client">Client executing this request</param> /// <param name="request">Request to authenticate</param> /// <param name="credentials">The credentials used for the authentication</param> /// <returns>The task the authentication is performed on</returns> public override async Task PreAuthenticate(IHttpClient client, IHttpRequestMessage request, ICredentials credentials) { // When the authorization failed or when the Authorization header is missing, we're just adding it (again) with the // new AccessToken. var authHeader = $"{_tokenType} {await Client.GetCurrentToken()}"; request.SetAuthorizationHeader(AuthHeader.Www, authHeader); }
/// <summary> /// Will be called when the authentication failed /// </summary> /// <param name="client">Client executing this request</param> /// <param name="request">Request to authenticate</param> /// <param name="credentials">The credentials used for the authentication</param> /// <param name="response">Response of the failed request</param> /// <returns>Task where the handler for a failed authentication gets executed</returns> public virtual async Task HandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response) { if (!CanHandleChallenge(client, request, credentials, response)) { throw new InvalidOperationException(); } await Client.GetCurrentToken(forceUpdate : true); }
/// <summary> /// Determines if the authentication module can handle the challenge sent with the response. /// </summary> /// <param name="client">The REST client the response is assigned to</param> /// <param name="request">The REST request the response is assigned to</param> /// <param name="credentials">The credentials to be used for the authentication</param> /// <param name="response">The response that returned the authentication challenge</param> /// <returns>true when the authenticator can handle the sent challenge</returns> public override bool CanHandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response) { if (HasAuthorizationToken) return false; if (response.StatusCode == HttpStatusCode.NotFound) return true; return base.CanHandleChallenge(client, request, credentials, response); }
/// <summary> /// Modifies the request to ensure that the authentication requirements are met. /// </summary> /// <param name="client">Client executing this request</param> /// <param name="request">Request to authenticate</param> /// <param name="credentials">The credentials used for the authentication</param> /// <returns>The task the authentication is performed on</returns> public override async Task PreAuthenticate(IHttpClient client, IHttpRequestMessage request, ICredentials credentials) { // When the authorization failed or when the Authorization header is missing, we're just adding it (again) with the // new AccessToken. var authHeader = $"{_tokenType} {await Client.GetCurrentToken().ConfigureAwait(false)}"; request.SetAuthorizationHeader(AuthHeader.Www, authHeader); }
/// <summary> /// Initializes a new instance of the <see cref="DefaultHttpResponseMessage"/> class. /// </summary> /// <param name="responseMessage">The response message to wrap</param> public DefaultHttpResponseMessage([NotNull] HttpResponseMessage responseMessage) { ResponseMessage = responseMessage; if (responseMessage.RequestMessage != null) _requestMessage = new DefaultHttpRequestMessage(responseMessage.RequestMessage); _content = responseMessage.Content.AsRestHttpContent(); _responseHttpHeaders = new DefaultHttpHeaders(responseMessage.Headers); }
/// <summary> /// Initializes a new instance of the <see cref="DefaultHttpResponseMessage"/> class. /// </summary> /// <param name="responseMessage">The response message to wrap</param> public DefaultHttpResponseMessage([NotNull] HttpResponseMessage responseMessage) { ResponseMessage = responseMessage; if (responseMessage.RequestMessage != null) { _requestMessage = new DefaultHttpRequestMessage(responseMessage.RequestMessage); } Content = responseMessage.Content.AsRestHttpContent(); _responseHttpHeaders = new DefaultHttpHeaders(responseMessage.Headers); }
/// <summary> /// Determines if the authentication module can handle the challenge sent with the response. /// </summary> /// <param name="client">The REST client the response is assigned to</param> /// <param name="request">The REST request the response is assigned to</param> /// <param name="credentials">The credentials to be used for the authentication</param> /// <param name="response">The response that returned the authentication challenge</param> /// <returns>true when the authenticator can handle the sent challenge</returns> public bool CanHandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response) { return(response .GetAuthenticationHeaderInfo(Header) .Where(x => _authenticators.ContainsKey(x.Name)) .Select(x => _authenticators[x.Name]) .Where(x => x.Authenticator.CanHandleChallenge(client, request, credentials, response)) .OrderByDescending(x => x.Security) .Select(x => x.Authenticator) .Any()); }
/// <summary> /// Determines if the authentication module can handle the challenge sent with the response. /// </summary> /// <param name="client">The REST client the response is assigned to</param> /// <param name="request">The REST request the response is assigned to</param> /// <param name="credentials">The credentials to be used for the authentication</param> /// <param name="response">The response that returned the authentication challenge</param> /// <returns>true when the authenticator can handle the sent challenge</returns> public override bool CanHandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response) { if (HasAuthorizationToken) { return(false); } if (response.StatusCode == HttpStatusCode.NotFound) { return(true); } return(base.CanHandleChallenge(client, request, credentials, response)); }
/// <summary> /// Will be called when the authentication failed /// </summary> /// <param name="client">Client executing this request</param> /// <param name="request">Request to authenticate</param> /// <param name="credentials">The credentials used for the authentication</param> /// <param name="response">Response of the failed request</param> /// <returns>Task where the handler for a failed authentication gets executed</returns> public async Task HandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response) { var authenticator = response .GetAuthenticationHeaderInfo(Header) .Where(x => _authenticators.ContainsKey(x.Name)) .Select(x => _authenticators[x.Name]) .Where(x => x.Authenticator.CanHandleChallenge(client, request, credentials, response)) .OrderByDescending(x => x.Security) .Select(x => x.Authenticator) .First(); await authenticator.HandleChallenge(client, request, credentials, response); }
/// <summary> /// Modifies the request to ensure that the authentication requirements are met. /// </summary> /// <param name="client">Client executing this request</param> /// <param name="request">Request to authenticate</param> /// <param name="credentials">The credentials used for the authentication</param> /// <returns>The task the authentication is performed on</returns> public Task PreAuthenticate(IHttpClient client, IHttpRequestMessage request, ICredentials credentials) { return(Task.Factory.StartNew(() => { if (!CanPreAuthenticate(client, request, credentials)) { throw new InvalidOperationException(); } var authHeaderValue = $"{AuthenticationMethod} {_authToken}"; request.SetAuthorizationHeader(_authHeader, authHeaderValue); })); }
/// <summary> /// Modifies the request to ensure that the authentication requirements are met. /// </summary> /// <param name="client">Client executing this request</param> /// <param name="request">Request to authenticate</param> /// <param name="credentials">The credentials used for the authentication</param> /// <returns>The task the authentication is performed on</returns> public async Task PreAuthenticate(IHttpClient client, IHttpRequestMessage request, ICredentials credentials) { if (!CanPreAuthenticate(client, request, credentials)) { throw new InvalidOperationException(); } var digestHeader = await GetDigestHeader(client, request, _authCredential).ConfigureAwait(false); var authHeaderValue = $"{AuthenticationMethod} {digestHeader}"; request.SetAuthorizationHeader(_authHeader, authHeaderValue); }
/// <summary> /// Will be called when the authentication failed /// </summary> /// <param name="client">Client executing this request</param> /// <param name="request">Request to authenticate</param> /// <param name="credentials">The credentials used for the authentication</param> /// <param name="response">Response of the failed request</param> /// <returns>Task where the handler for a failed authentication gets executed</returns> public Task HandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response) { return(Task.Factory.StartNew(() => { if (!CanHandleChallenge(client, request, credentials, response)) { throw new InvalidOperationException(); } var responseUri = client.GetRequestUri(request, response); _authCredential = credentials.GetCredential(responseUri, AuthenticationMethod); _authToken = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{_authCredential.UserName}:{_authCredential.Password}")); })); }
public static Uri GetRequestUri([CanBeNull] this IHttpClient client, [NotNull] IHttpRequestMessage request) { if (client?.BaseAddress == null) { return(request.RequestUri); } if (request.RequestUri != null) { return(new Uri(client.BaseAddress, request.RequestUri)); } return(client.BaseAddress); }
/// <summary> /// Will be called when the authentication failed /// </summary> /// <param name="client">Client executing this request</param> /// <param name="request">Request to authenticate</param> /// <param name="credentials">The credentials used for the authentication</param> /// <param name="response">Response of the failed request</param> /// <returns>Task where the handler for a failed authentication gets executed</returns> public Task HandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response) { return(Task.Factory.StartNew(() => { if (!CanHandleChallenge(client, request, credentials, response)) { throw new InvalidOperationException(); } var responseUri = client.GetRequestUri(request, response); _authCredential = credentials.GetCredential(responseUri, AuthenticationMethod); var authModeInfo = response.GetAuthenticationMethodValue(_authHeader, AuthenticationMethod); ParseResponseHeader(authModeInfo); })); }
public static Uri GetRequestUri([CanBeNull] this IHttpClient client, [NotNull] IHttpRequestMessage request, [NotNull] IHttpResponseMessage response) { var requestUri = client.GetRequestUri(request); IEnumerable <string> locationValues; if (!response.Headers.TryGetValues("Location", out locationValues)) { return(requestUri); } var location = locationValues.FirstOrDefault(); if (string.IsNullOrWhiteSpace(location)) { return(requestUri); } return(new Uri(requestUri, location)); }
/// <summary> /// Modifies the request to ensure that the authentication requirements are met. /// </summary> /// <param name="client">Client executing this request</param> /// <param name="request">Request to authenticate</param> /// <param name="credentials">The credentials used for the authentication</param> /// <returns>The task the authentication is performed on</returns> public Task PreAuthenticate(IHttpClient client, IHttpRequestMessage request, ICredentials credentials) { if (!HasAuthorizationToken) { throw new InvalidOperationException(); } var authHeaderValue = $"{AuthenticationMethod} {_authToken}"; request.SetAuthorizationHeader(_authHeader, authHeaderValue); #if ASYNC_PCL return(Task.FromResult(0)); #else return(new Task(() => { })); #endif }
/// <inheritdoc/> public override bool CanHandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response) { // Get authentication header using the method specified by <code>_tokenType</code> or <code>OAuth</code> var authHeaderInfo = response .GetAuthenticationHeaderInfo(AuthHeader.Www) .FirstOrDefault( x => string.Equals(x.Name, _tokenType, StringComparison.OrdinalIgnoreCase) || string.Equals(x.Name, "OAuth", StringComparison.OrdinalIgnoreCase)); if (authHeaderInfo == null) { return(false); } // Check for WWW-Authenticate when status code is 401 (Unauthorized) if (response.StatusCode == HttpStatusCode.Unauthorized) { return(authHeaderInfo.Values["error"].Any(x => string.Equals(x, "invalid_token"))); } // Not a 400 (Bad Request)? Cannot handle challenge. if (response.StatusCode != HttpStatusCode.BadRequest) { return(false); } // Check for Facebooks broken WWW-Authenticate var isFacebook = authHeaderInfo.Values[string.Empty].Any(x => x.Contains("Facebook")); if (!isFacebook) { return(false); } if (!authHeaderInfo.Values[string.Empty].Any(x => x.Equals("invalid_token", StringComparison.OrdinalIgnoreCase))) { return(false); } if (!base.CanHandleChallenge(client, request, credentials, response)) { return(false); } return(true); }
/// <summary> /// Will be called when the authentication failed /// </summary> /// <param name="client">Client executing this request</param> /// <param name="request">Request to authenticate</param> /// <param name="credentials">The credentials used for the authentication</param> /// <param name="response">Response of the failed request</param> /// <returns>Task where the handler for a failed authentication gets executed</returns> public Task HandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response) { if (!CanHandleChallenge(client, request, credentials, response)) { throw new InvalidOperationException(); } var responseUri = client.GetRequestUri(request, response); _authCredential = credentials.GetCredential(responseUri, AuthenticationMethod); var authModeInfo = response.GetAuthenticationMethodValue(_authHeader, AuthenticationMethod); ParseResponseHeader(authModeInfo); #if USE_TASKEX return(TaskEx.FromResult(0)); #else return(Task.FromResult(0)); #endif }
/// <summary> /// Determines if the authentication module can handle the challenge sent with the response. /// </summary> /// <param name="client">The REST client the response is assigned to</param> /// <param name="request">The REST request the response is assigned to</param> /// <param name="credentials">The credentials to be used for the authentication</param> /// <param name="response">The response that returned the authentication challenge</param> /// <returns>true when the authenticator can handle the sent challenge</returns> public virtual bool CanHandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response) { // No refresh token? Cannot handle challenge if (string.IsNullOrEmpty(Client.RefreshToken)) { return(false); } var currentChallenge = DateTimeOffset.UtcNow; if (_lastChallenge.HasValue) { var safetyMargin = TimeSpan.FromSeconds(60); if (currentChallenge < _lastChallenge.Value + safetyMargin) { return(false); } } _lastChallenge = currentChallenge; return(true); }
public static HttpRequestMessage AsHttpRequestMessage([NotNull] this IHttpRequestMessage message) { var req = message as DefaultHttpRequestMessage; if (req != null) { return(req.RequestMessage); } var result = new HttpRequestMessage(message.Method.ToHttpMethod(), message.RequestUri); if (message.Version != null) { result.Version = message.Version; } message.Headers.CopyTo(result.Headers); if (message.Content != null) { result.Content = message.Content.AsHttpContent(); } return(result); }
public async Task <string> Request(IHttpRequestMessage requestMessage) { HttpResponseMessage responseMessage; var messageContent = new StringContent(requestMessage.Message ?? string.Empty, Encoding.UTF8, "application/json"); switch (requestMessage.HttpMessageMethod) { case Enums.HttpMessageMethod.Post: responseMessage = await httpClient.PostAsync(requestMessage.UrlPath, messageContent).ConfigureAwait(false); break; case Enums.HttpMessageMethod.Delete: responseMessage = await httpClient.DeleteAsync(requestMessage.UrlPath, messageContent).ConfigureAwait(false); break; case Enums.HttpMessageMethod.Put: responseMessage = await httpClient.PutAsync(requestMessage.UrlPath, messageContent).ConfigureAwait(false); break; default: responseMessage = new HttpResponseMessage(); break; } CheckStatusCode(responseMessage); var responseString = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); //fire event with response message ClientMessage(responseMessage.StatusCode, requestMessage.Device.Device ?? "n/a", responseString); return(responseString); }
/// <summary> /// Modifies the request to ensure that the authentication requirements are met. /// </summary> /// <param name="client">Client executing this request</param> /// <param name="request">Request to authenticate</param> /// <param name="credentials">The credentials used for the authentication</param> /// <returns>The task the authentication is performed on</returns> public Task PreAuthenticate(IHttpClient client, IHttpRequestMessage request, ICredentials credentials) { return Task.Factory.StartNew(() => { if (!CanPreAuthenticate(client, request, credentials)) { throw new InvalidOperationException(); } var authHeaderValue = $"{AuthenticationMethod} {_authToken}"; request.SetAuthorizationHeader(_authHeader, authHeaderValue); }); }
/// <summary> /// Will be called when the authentication failed /// </summary> /// <param name="client">Client executing this request</param> /// <param name="request">Request to authenticate</param> /// <param name="credentials">The credentials used for the authentication</param> /// <param name="response">Response of the failed request</param> /// <returns>Task where the handler for a failed authentication gets executed</returns> public Task HandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response) { return Task.Factory.StartNew(() => { if (!CanHandleChallenge(client, request, credentials, response)) { throw new InvalidOperationException(); } var responseUri = client.GetRequestUri(request, response); _authCredential = credentials.GetCredential(responseUri, AuthenticationMethod); _authToken = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{_authCredential.UserName}:{_authCredential.Password}")); }); }
/// <summary> /// Determines if the authentication module can handle the challenge sent with the response. /// </summary> /// <param name="client">The REST client the response is assigned to</param> /// <param name="request">The REST request the response is assigned to</param> /// <param name="credentials">The credentials to be used for the authentication</param> /// <param name="response">The response that returned the authentication challenge</param> /// <returns>true when the authenticator can handle the sent challenge</returns> public virtual bool CanHandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response) { return !string.IsNullOrEmpty(Client.RefreshToken); }
/// <summary> /// Does the authentication module supports pre-authentication? /// </summary> /// <param name="client">Client executing this request</param> /// <param name="request">Request to authenticate</param> /// <param name="credentials">The credentials to be used for the authentication</param> /// <returns>true when the authentication module supports pre-authentication</returns> public bool CanPreAuthenticate(IHttpClient client, IHttpRequestMessage request, ICredentials credentials) { return(HasAuthorizationToken); }
/// <inheritdoc/> public override bool CanHandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response) { // Get authentication header using the method specified by <code>_tokenType</code> or <code>OAuth</code> var authHeaderInfo = response .GetAuthenticationHeaderInfo(AuthHeader.Www) .FirstOrDefault( x => string.Equals(x.Name, _tokenType, StringComparison.OrdinalIgnoreCase) || string.Equals(x.Name, "OAuth", StringComparison.OrdinalIgnoreCase)); if (authHeaderInfo == null) return false; // Check for WWW-Authenticate when status code is 401 (Unauthorized) if (response.StatusCode == HttpStatusCode.Unauthorized) return authHeaderInfo.Values["error"].Any(x => string.Equals(x, "invalid_token")); // Not a 400 (Bad Request)? Cannot handle challenge. if (response.StatusCode != HttpStatusCode.BadRequest) return false; // Check for Facebooks broken WWW-Authenticate var isFacebook = authHeaderInfo.Values[string.Empty].Any(x => x.Contains("Facebook")); if (!isFacebook) return false; if (!authHeaderInfo.Values[string.Empty].Any(x => x.Equals("invalid_token", StringComparison.OrdinalIgnoreCase))) return false; if (!base.CanHandleChallenge(client, request, credentials, response)) return false; return true; }
/// <summary> /// Does the authentication module supports pre-authentication for the given <see cref="IHttpRequestMessage" />? /// </summary> /// <param name="client">Client executing this request</param> /// <param name="request">Request to authenticate</param> /// <param name="credentials">The credentials to be used for the authentication</param> /// <returns>true when the authentication module supports pre-authentication</returns> public override bool CanPreAuthenticate(IHttpClient client, IHttpRequestMessage request, ICredentials credentials) { return true; }
/// <summary> /// Does the authentication module supports pre-authentication for the given <see cref="IHttpRequestMessage" />? /// </summary> /// <param name="client">Client executing this request</param> /// <param name="request">Request to authenticate</param> /// <param name="credentials">The credentials to be used for the authentication</param> /// <returns>true when the authentication module supports pre-authentication</returns> public bool CanPreAuthenticate(IHttpClient client, IHttpRequestMessage request, ICredentials credentials) { return _authenticators.Values.Any(x => x.Authenticator.CanPreAuthenticate(client, request, credentials)); }
/// <summary> /// Does the authentication module supports pre-authentication for the given <see cref="IHttpRequestMessage" />? /// </summary> /// <param name="client">Client executing this request</param> /// <param name="request">Request to authenticate</param> /// <param name="credentials">The credentials to be used for the authentication</param> /// <returns>true when the authentication module supports pre-authentication</returns> public bool CanPreAuthenticate(IHttpClient client, IHttpRequestMessage request, ICredentials credentials) { return false; }
/// <summary> /// Will be called when the authentication failed /// </summary> /// <param name="client">Client executing this request</param> /// <param name="request">Request to authenticate</param> /// <param name="credentials">The credentials used for the authentication</param> /// <param name="response">Response of the failed request</param> /// <returns>Task where the handler for a failed authentication gets executed</returns> public Task HandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response) { throw new NotSupportedException(); }
/// <summary> /// Determines if the authentication module can handle the challenge sent with the response. /// </summary> /// <param name="client">The HTTP client the response is assigned to</param> /// <param name="request">The HTTP request the response is assigned to</param> /// <param name="credentials">The credentials to be used for the authentication</param> /// <param name="response">The response that returned the authentication challenge</param> /// <returns>true when the authenticator can handle the sent challenge</returns> public virtual bool CanHandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response) { return false; }
/// <summary> /// Modifies the request to ensure that the authentication requirements are met. /// </summary> /// <param name="client">Client executing this request</param> /// <param name="request">Request to authenticate</param> /// <param name="credentials">The credentials used for the authentication</param> /// <returns>The task the authentication is performed on</returns> public Task PreAuthenticate(IHttpClient client, IHttpRequestMessage request, ICredentials credentials) { throw new NotSupportedException(); }
/// <summary> /// Determines if the authentication module can handle the challenge sent with the response. /// </summary> /// <param name="client">The REST client the response is assigned to</param> /// <param name="request">The REST request the response is assigned to</param> /// <param name="credentials">The credentials to be used for the authentication</param> /// <param name="response">The response that returned the authentication challenge</param> /// <returns>true when the authenticator can handle the sent challenge</returns> public virtual bool CanHandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response) { // No refresh token? Cannot handle challenge if (string.IsNullOrEmpty(Client.RefreshToken)) return false; var currentChallenge = DateTimeOffset.UtcNow; if (_lastChallenge.HasValue) { var safetyMargin = TimeSpan.FromSeconds(60); if (currentChallenge < _lastChallenge.Value + safetyMargin) return false; } _lastChallenge = currentChallenge; return true; }
/// <summary> /// Asynchronously send a request /// </summary> /// <param name="request">The request do send</param> /// <param name="cancellationToken">The cancellation token used to signal an abortion</param> /// <returns>The task to query the response</returns> public async Task<IHttpResponseMessage> SendAsync(IHttpRequestMessage request, CancellationToken cancellationToken) { var uri = new Uri(BaseAddress, request.RequestUri); var wr = _httpClientFactory.CreateWebRequest(uri); if (wr.SupportsCookieContainer && CookieContainer != null) wr.CookieContainer = CookieContainer; if (Credentials != null) wr.Credentials = Credentials; wr.Method = request.Method.ToString(); #if !PCL wr.Proxy = Proxy ?? System.Net.WebRequest.DefaultWebProxy; #endif // Combine all headers into one header collection var headers = new GenericHttpHeaders(); if (request.Content?.Headers != null) { foreach (var header in request.Content.Headers.Where(x => !headers.Contains(x.Key))) { headers.TryAddWithoutValidation(header.Key, header.Value); } } if (request.Headers != null) { foreach (var header in request.Headers.Where(x => !headers.Contains(x.Key))) { headers.TryAddWithoutValidation(header.Key, header.Value); } } if (DefaultRequestHeaders != null) { foreach (var header in DefaultRequestHeaders.Where(x => !headers.Contains(x.Key))) { headers.TryAddWithoutValidation(header.Key, header.Value); } } bool hasContentLength = false; foreach (var header in headers) { var value = string.Join(",", header.Value); SetWebRequestHeaderValue(wr, header.Key, value); if (!hasContentLength && string.Equals(header.Key, "content-length", StringComparison.OrdinalIgnoreCase)) hasContentLength = true; } if (request.Content != null) { // Add content length if not provided by the user. if (!hasContentLength) { long contentLength; if (request.Content.TryComputeLength(out contentLength)) { #if PCL || NETFX_CORE || WINDOWS_STORE wr.Headers[HttpRequestHeader.ContentLength] = contentLength.ToString(); #else wr.ContentLength = contentLength; #endif } } try { #if PCL && ASYNC_PCL var getRequestStreamAsync = Task.Factory.FromAsync<Stream>(wr.BeginGetRequestStream, wr.EndGetRequestStream, null); var requestStream = await getRequestStreamAsync.HandleCancellation(cancellationToken); #else var requestStream = await wr.GetRequestStreamAsync().HandleCancellation(cancellationToken); #endif using (requestStream) { var temp = new MemoryStream(); await request.Content.CopyToAsync(temp); var buffer = temp.ToArray(); await requestStream.WriteAsync(buffer, 0, buffer.Length, cancellationToken); await requestStream.FlushAsync(cancellationToken); } } catch (OperationCanceledException) { wr.Abort(); throw; } } try { #if PCL && ASYNC_PCL var getResponseAsync = Task.Factory.FromAsync<WebResponse>(wr.BeginGetResponse, wr.EndGetResponse, null); var response = await getResponseAsync.HandleCancellation(cancellationToken); #else var response = await wr.GetResponseAsync().HandleCancellation(cancellationToken); #endif var httpWebResponse = response as HttpWebResponse; if (httpWebResponse == null) { response.Dispose(); throw new ProtocolViolationException("No HTTP request") { Data = { { "URI", wr.RequestUri }, }, }; } return new DefaultHttpResponseMessage(request, httpWebResponse); } catch (WebException ex) { var httpWebResponse = (HttpWebResponse)ex.Response; return new DefaultHttpResponseMessage(request, httpWebResponse, ex); } catch (OperationCanceledException) { wr.Abort(); throw; } }
/// <summary> /// Asynchronously send a request /// </summary> /// <param name="request">The request do send</param> /// <param name="cancellationToken">The cancellation token used to signal an abortion</param> /// <returns>The task to query the response</returns> public async Task<IHttpResponseMessage> SendAsync(IHttpRequestMessage request, CancellationToken cancellationToken) { var requestMessage = request.AsHttpRequestMessage(); var response = await Client.SendAsync(requestMessage, cancellationToken); return new DefaultHttpResponseMessage(requestMessage, response); }
/// <summary> /// Will be called when the authentication failed /// </summary> /// <param name="client">Client executing this request</param> /// <param name="request">Request to authenticate</param> /// <param name="credentials">The credentials used for the authentication</param> /// <param name="response">Response of the failed request</param> /// <returns>Task where the handler for a failed authentication gets executed</returns> public virtual async Task HandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response) { if (!CanHandleChallenge(client, request, credentials, response)) throw new InvalidOperationException(); await Client.GetCurrentToken(forceUpdate: true); }
/// <summary> /// Does the authentication module supports pre-authentication? /// </summary> /// <param name="client">Client executing this request</param> /// <param name="request">Request to authenticate</param> /// <param name="credentials">The credentials to be used for the authentication</param> /// <returns>true when the authentication module supports pre-authentication</returns> public bool CanPreAuthenticate(IHttpClient client, IHttpRequestMessage request, ICredentials credentials) { return HasAuthorizationToken; }
private async Task <string> GetDigestHeader(IHttpClient client, IHttpRequestMessage request, NetworkCredential credential) { _nc = _nc + 1; var uri = client.GetRequestUri(request); var pathAndQuery = uri.GetComponents(UriComponents.PathAndQuery, UriFormat.SafeUnescaped); if (_algorithm == Algorithm.Undefined) { throw new InvalidOperationException("Algorithm not set"); } string ha2, digestResponse; var ha1 = CalculateMd5Hash($"{credential.UserName}:{_realm}:{credential.Password}"); string algorithm; switch (_algorithm) { case Algorithm.MD5sess: ha1 = CalculateMd5Hash($"{ha1}:{_nonce}:{_cnonce}"); algorithm = "MD5-sess"; break; default: algorithm = "MD5"; break; } string qop; switch (_qop) { case QualityOfProtection.Auth: qop = "auth"; break; case QualityOfProtection.AuthInt: qop = "auth-int"; break; default: qop = null; break; } switch (_qop) { case QualityOfProtection.AuthInt: { byte[] entityBody; if (request.Content == null) { entityBody = new byte[0]; } else { await request.Content.LoadIntoBufferAsync().ConfigureAwait(false); entityBody = await request.Content.ReadAsByteArrayAsync().ConfigureAwait(false); } ha2 = CalculateMd5Hash(entityBody); } ha2 = CalculateMd5Hash($"{request.Method}:{pathAndQuery}:{ha2}"); break; default: ha2 = CalculateMd5Hash($"{request.Method}:{pathAndQuery}"); break; } switch (_qop) { case QualityOfProtection.AuthInt: case QualityOfProtection.Auth: digestResponse = CalculateMd5Hash($"{ha1}:{_nonce}:{_nc:D8}:{_cnonce}:{qop}:{ha2}"); break; default: digestResponse = CalculateMd5Hash($"{ha1}:{_nonce}:{ha2}"); break; } var result = new StringBuilder(); result .AppendFormat("username=\"{0}\"", credential.UserName) .AppendFormat(", realm=\"{0}\"", _realm) .AppendFormat(", nonce=\"{0}\"", _nonce) .AppendFormat(", uri=\"{0}\"", pathAndQuery) .AppendFormat(", nc={0:D08}", _nc); if (algorithm != "MD5") { result.AppendFormat(", algorithm=\"{0}\"", algorithm); } if (!string.IsNullOrEmpty(qop)) { result .AppendFormat(", cnonce=\"{0}\"", _cnonce) .AppendFormat(", qop={0}", qop); } if (!string.IsNullOrEmpty(_opaque)) { result .AppendFormat(", opaque=\"{0}\"", _opaque); } result .AppendFormat(", response=\"{0}\"", digestResponse); return(result.ToString()); }
public System.Threading.Tasks.Task PreAuthenticate(IHttpClient client, IHttpRequestMessage request, System.Net.ICredentials credentials) { throw new NotImplementedException(); }
public bool CanPreAuthenticate(IHttpClient client, IHttpRequestMessage request, System.Net.ICredentials credentials) { return(false); }
public System.Threading.Tasks.Task HandleChallenge(IHttpClient client, IHttpRequestMessage request, System.Net.ICredentials credentials, IHttpResponseMessage response) { throw new NotImplementedException(); }
public bool CanHandleChallenge(IHttpClient client, IHttpRequestMessage request, System.Net.ICredentials credentials, IHttpResponseMessage response) { return false; }
/// <summary> /// Determines if the authentication module can handle the challenge sent with the response. /// </summary> /// <param name="client">The REST client the response is assigned to</param> /// <param name="request">The REST request the response is assigned to</param> /// <param name="credentials">The credentials to be used for the authentication</param> /// <param name="response">The response that returned the authentication challenge</param> /// <returns>true when the authenticator can handle the sent challenge</returns> public bool CanHandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response) { return response .GetAuthenticationHeaderInfo(Header) .Where(x => _authenticators.ContainsKey(x.Name)) .Select(x => _authenticators[x.Name]) .Where(x => x.Authenticator.CanHandleChallenge(client, request, credentials, response)) .OrderByDescending(x => x.Security) .Select(x => x.Authenticator) .Any(); }
/// <summary> /// Modifies the request to ensure that the authentication requirements are met. /// </summary> /// <param name="client">Client executing this request</param> /// <param name="request">Request to authenticate</param> /// <param name="credentials">The credentials used for the authentication</param> /// <returns>The task the authentication is performed on</returns> public async Task PreAuthenticate(IHttpClient client, IHttpRequestMessage request, ICredentials credentials) { if (!CanPreAuthenticate(client, request, credentials)) throw new InvalidOperationException(); var digestHeader = await GetDigestHeader(client, request, _authCredential); var authHeaderValue = $"{AuthenticationMethod} {digestHeader}"; request.SetAuthorizationHeader(_authHeader, authHeaderValue); }
/// <summary> /// Does the authentication module supports pre-authentication for the given <see cref="IHttpRequestMessage" />? /// </summary> /// <param name="client">Client executing this request</param> /// <param name="request">Request to authenticate</param> /// <param name="credentials">The credentials to be used for the authentication</param> /// <returns>true when the authentication module supports pre-authentication</returns> public abstract bool CanPreAuthenticate(IHttpClient client, IHttpRequestMessage request, ICredentials credentials);
/// <summary> /// Determines if the authentication module can handle the challenge sent with the response. /// </summary> /// <param name="client">The REST client the response is assigned to</param> /// <param name="request">The REST request the response is assigned to</param> /// <param name="credentials">The credentials to be used for the authentication</param> /// <param name="response">The response that returned the authentication challenge</param> /// <returns>true when the authenticator can handle the sent challenge</returns> public virtual bool CanHandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response) { // No credentials defined? if (credentials == null) return false; // No challenge header found? var authModeInfo = response.GetAuthenticationMethodValue(_authHeader, AuthenticationMethod); if (authModeInfo == null) return false; // Search for credential for request URI var responseUri = client.GetRequestUri(request, response); var credential = credentials.GetCredential(responseUri, AuthenticationMethod); if (credential == null) return false; // Did we already try to use the found credentials? if (ReferenceEquals(credential, _authCredential)) { // Yes, so we don't retry the authentication. return false; } return true; }
/// <summary> /// Will be called when the authentication failed /// </summary> /// <param name="client">Client executing this request</param> /// <param name="request">Request to authenticate</param> /// <param name="credentials">The credentials used for the authentication</param> /// <param name="response">Response of the failed request</param> /// <returns>Task where the handler for a failed authentication gets executed</returns> public Task HandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response) { return Task.Factory.StartNew(() => { if (!CanHandleChallenge(client, request, credentials, response)) throw new InvalidOperationException(); var responseUri = client.GetRequestUri(request, response); _authCredential = credentials.GetCredential(responseUri, AuthenticationMethod); var authModeInfo = response.GetAuthenticationMethodValue(_authHeader, AuthenticationMethod); ParseResponseHeader(authModeInfo); }); }
public bool CanHandleChallenge(IHttpClient client, IHttpRequestMessage request, System.Net.ICredentials credentials, IHttpResponseMessage response) { return(false); }
private async Task<string> GetDigestHeader(IHttpClient client, IHttpRequestMessage request, NetworkCredential credential) { _nc = _nc + 1; var uri = client.GetRequestUri(request); var pathAndQuery = uri.GetComponents(UriComponents.PathAndQuery, UriFormat.SafeUnescaped); if (_algorithm == Algorithm.Undefined) throw new InvalidOperationException("Algorithm not set"); string ha2, digestResponse; var ha1 = CalculateMd5Hash(string.Format("{0}:{1}:{2}", credential.UserName, _realm, credential.Password)); string algorithm; switch (_algorithm) { case Algorithm.MD5sess: ha1 = CalculateMd5Hash(string.Format("{0}:{1}:{2}", ha1, _nonce, _cnonce)); algorithm = "MD5-sess"; break; default: algorithm = "MD5"; break; } string qop; switch (_qop) { case QualityOfProtection.Auth: qop = "auth"; break; case QualityOfProtection.AuthInt: qop = "auth-int"; break; default: qop = null; break; } switch (_qop) { case QualityOfProtection.AuthInt: { byte[] entityBody; if (request.Content == null) { entityBody = new byte[0]; } else { await request.Content.LoadIntoBufferAsync(); entityBody = await request.Content.ReadAsByteArrayAsync(); } ha2 = CalculateMd5Hash(entityBody); } ha2 = CalculateMd5Hash(string.Format("{0}:{1}:{2}", request.Method, pathAndQuery, ha2)); break; default: ha2 = CalculateMd5Hash(string.Format("{0}:{1}", request.Method, pathAndQuery)); break; } switch (_qop) { case QualityOfProtection.AuthInt: case QualityOfProtection.Auth: digestResponse = CalculateMd5Hash(string.Format("{0}:{1}:{2:D8}:{3}:{4}:{5}", ha1, _nonce, _nc, _cnonce, qop, ha2)); break; default: digestResponse = CalculateMd5Hash(string.Format("{0}:{1}:{2}", ha1, _nonce, ha2)); break; } var result = new StringBuilder(); result .AppendFormat("username=\"{0}\"", credential.UserName) .AppendFormat(", realm=\"{0}\"", _realm) .AppendFormat(", nonce=\"{0}\"", _nonce) .AppendFormat(", uri=\"{0}\"", pathAndQuery) .AppendFormat(", nc={0:D08}", _nc); if (algorithm != "MD5") result.AppendFormat(", algorithm=\"{0}\"", algorithm); if (!string.IsNullOrEmpty(qop)) { result .AppendFormat(", cnonce=\"{0}\"", _cnonce) .AppendFormat(", qop={0}", qop); } if (!string.IsNullOrEmpty(_opaque)) result .AppendFormat(", opaque=\"{0}\"", _opaque); result .AppendFormat(", response=\"{0}\"", digestResponse); return result.ToString(); }
/// <summary> /// Modifies the request to ensure that the authentication requirements are met. /// </summary> /// <param name="client">Client executing this request</param> /// <param name="request">Request to authenticate</param> /// <param name="credentials">The credentials used for the authentication</param> /// <returns>The task the authentication is performed on</returns> public async Task PreAuthenticate(IHttpClient client, IHttpRequestMessage request, ICredentials credentials) { foreach (var authenticator in _authenticators.Values.Select(x => x.Authenticator).Where(x => x.CanPreAuthenticate(client, request, credentials))) { await authenticator.PreAuthenticate(client, request, credentials); } }