Beispiel #1
0
 public static void AddHeaders(this HttpRequestMessage request, IEnumerable <HttpHeader> headers)
 {
     foreach (var header in headers.GroupBy(h => h.Name))
     {
         request.AddHeader(header.Key, header.SelectMany(h => h.Values));
     }
 }
        private static HttpRequestMessage CreateRequestMessage(Message message, HttpRequestMessageProperty requestMessageProperty)
        {
            Fx.Assert(message != null, "The 'message' parameter should not be null.");
            Fx.Assert(requestMessageProperty != null, "The 'requestMessageProperty' parameter should not be null.");

            HttpRequestMessage request = new HttpRequestMessage();

            request.RequestUri = message.Properties.Via;

            Fx.Assert(requestMessageProperty.Method != null, "The HttpRequestMessageProperty class ensures the 'Method' property will never be null.");
            request.Method = new HttpMethod(requestMessageProperty.Method);

            request.Content = CreateMessageContent(message, requestMessageProperty.SuppressEntityBody);

            WebHeaderCollection headers = requestMessageProperty.Headers;

            foreach (string headerKey in headers.AllKeys)
            {
                request.AddHeader(headerKey, headers[headerKey]);
            }

            request.CopyPropertiesFromMessage(message);

            return(request);
        }
Beispiel #3
0
        public override void Run()
        {
            HttpClient httpClient = clientFactory.GetHttpClient();

            PreemptivelySetAuthCredentials(httpClient);
            HttpRequestMessage request = null;

            if (Sharpen.Runtime.EqualsIgnoreCase(method, "PUT"))
            {
                HttpPut putRequest = new HttpPut(url.ToExternalForm());
                putRequest.SetEntity(multiPart);
                request = putRequest;
            }
            else
            {
                if (Sharpen.Runtime.EqualsIgnoreCase(method, "POST"))
                {
                    HttpPost postRequest = new HttpPost(url.ToExternalForm());
                    postRequest.SetEntity(multiPart);
                    request = postRequest;
                }
                else
                {
                    throw new ArgumentException("Invalid request method: " + method);
                }
            }
            request.AddHeader("Accept", "*/*");
            ExecuteRequest(httpClient, request);
        }
Beispiel #4
0
        public void Setup()
        {
            {
                S3Config config = new S3Config();
                config.Region      = AwsRegion.EuWest1;
                config.Credentials = new StringAccessKey("keyidkeyidkeyidkeyid", "accesskeyacceskey123accesskeyacceskey123");

                IOptions <S3Config> options = Options.Create(config);

                SigningKeyBuilder signingKeyBuilder = new SigningKeyBuilder(options, NullLogger <SigningKeyBuilder> .Instance);
                ScopeBuilder      scopeBuilder      = new ScopeBuilder(options);
                SignatureBuilder  signatureBuilder  = new SignatureBuilder(signingKeyBuilder, scopeBuilder, NullLogger <SignatureBuilder> .Instance, options);

                _builder = new HeaderAuthorizationBuilder(options, scopeBuilder, signatureBuilder, NullLogger <HeaderAuthorizationBuilder> .Instance);

                _request = new DummyRequest();
                _request.SetHeader(AmzHeaders.XAmzContentSha256, "UNSIGNED-PAYLOAD");
            }

            {
                _request2    = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, "https://dummyurl");
                _credentials = new ImmutableCredentials("keyidkeyidkeyidkeyid", "accesskeyacceskey123accesskeyacceskey123", null);

                // Add required headers
                _request2.AddHeader(HeaderKeys.XAmzDateHeader, DateTime.UtcNow.ToIso8601BasicDateTime());

                // Add conditional headers
                _request2.AddHeaderIf(_credentials.UseToken, HeaderKeys.XAmzSecurityTokenHeader, _credentials.Token);
                _request2.AddHeaderIf(!_request2.Headers.Contains(HeaderKeys.HostHeader), HeaderKeys.HostHeader, _request2.RequestUri.Host);
            }
        }
Beispiel #5
0
 private void AddRequestHeaders(HttpRequestMessage request)
 {
     foreach (string requestHeaderKey in requestHeaders.Keys)
     {
         request.AddHeader(requestHeaderKey, requestHeaders[requestHeaderKey].ToString
                               ());
     }
 }
 protected internal virtual void AddRequestHeaders(HttpRequestMessage request)
 {
     foreach (string requestHeaderKey in requestHeaders.Keys)
     {
         request.AddHeader(requestHeaderKey, requestHeaders.Get(requestHeaderKey).ToString
                               ());
     }
 }
Beispiel #7
0
 public override void ConfigureHttpRequestMessage(HttpRequestMessage message)
 {
     message.Method     = new HttpMethod(this.listenerHttpContext.listenerContext.Request.HttpMethod);
     message.RequestUri = this.listenerHttpContext.listenerContext.Request.Url;
     foreach (string webHeaderKey in this.listenerHttpContext.listenerContext.Request.Headers.Keys)
     {
         message.AddHeader(webHeaderKey, this.listenerHttpContext.listenerContext.Request.Headers[webHeaderKey]);
     }
     message.Properties.Add(RemoteEndpointMessageProperty.Name, new RemoteEndpointMessageProperty(this.listenerHttpContext.listenerContext.Request.RemoteEndPoint));
 }
        public override void Run()
        {
            HttpClient httpClient = clientFactory.GetHttpClient();

            PreemptivelySetAuthCredentials(httpClient);
            HttpRequestMessage request = CreateConcreteRequest();

            request.AddHeader("Accept", "*/*");
            AddRequestHeaders(request);
            ExecuteRequest(httpClient, request);
        }
        public virtual void Run()
        {
            HttpClient httpClient           = clientFactory.GetHttpClient();
            ClientConnectionManager manager = httpClient.GetConnectionManager();
            HttpRequestMessage      request = CreateConcreteRequest();

            PreemptivelySetAuthCredentials(httpClient);
            request.AddHeader("Accept", "multipart/related, application/json");
            AddRequestHeaders(request);
            SetBody(request);
            ExecuteRequest(httpClient, request);
        }
Beispiel #10
0
            public override void ConfigureHttpRequestMessage(HttpRequestMessage message)
            {
                message.Method     = new HttpMethod(this.hostedHttpContext.result.GetHttpMethod());
                message.RequestUri = this.hostedHttpContext.result.RequestUri;
                foreach (string webHeaderKey in this.hostedHttpContext.result.Application.Context.Request.Headers.Keys)
                {
                    message.AddHeader(webHeaderKey, this.hostedHttpContext.result.Application.Context.Request.Headers[webHeaderKey]);
                }

                HostedRequestContainer        requestContainer       = new HostedRequestContainer(this.hostedHttpContext.result);
                RemoteEndpointMessageProperty remoteEndpointProperty = new RemoteEndpointMessageProperty(requestContainer);

                message.Properties.Add(RemoteEndpointMessageProperty.Name, remoteEndpointProperty);
            }
Beispiel #11
0
        private static void AddHeaders(
            HttpRequestMessage request,
            DateTime now,
            string serviceName,
            ImmutableCredentials credentials,
            string contentHash)
        {
            // Add required headers
            request.AddHeader(HeaderKeys.XAmzDateHeader, now.ToIso8601BasicDateTime());

            // Add conditional headers
            request.AddHeaderIf(credentials.UseToken, HeaderKeys.XAmzSecurityTokenHeader, credentials.Token);
            request.AddHeaderIf(!request.Headers.Contains(HeaderKeys.HostHeader), HeaderKeys.HostHeader, request.RequestUri !.Host);
            request.AddHeaderIf(serviceName == ServiceName.S3, HeaderKeys.XAmzContentSha256Header, contentHash);
        }
Beispiel #12
0
        public async Task <(int statusCode, IDictionary <string, string> headers, Stream?responseStream)> SendRequestAsync(HttpMethod method, string url, IReadOnlyDictionary <string, string>?headers = null, Stream?dataStream = null, CancellationToken cancellationToken = default)
        {
            HttpResponseMessage httpResponse;

            using (HttpRequestMessage httpRequest = new HttpRequestMessage(ConvertToMethod(method), url))
            {
                if (dataStream != null)
                {
                    httpRequest.Content = new StreamContent(dataStream);
                }

                //Map all the headers to the HTTP request headers. We have to do this after setting the content as some headers are related to content
                if (headers != null)
                {
                    foreach (KeyValuePair <string, string> item in headers)
                    {
                        httpRequest.AddHeader(item.Key, item.Value);
                    }
                }

                _logger.LogTrace("Sending HTTP request");

                httpResponse = await _client.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
            }

            _logger.LogDebug("Got an {status} response with {Code}", httpResponse.IsSuccessStatusCode ? "successful" : "unsuccessful", httpResponse.StatusCode);

            IDictionary <string, string> responseHeaders = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            foreach (KeyValuePair <string, IEnumerable <string> > header in httpResponse.Headers)
            {
                responseHeaders.Add(header.Key, header.Value.First());
            }

            Stream?responseStream = null;

            if (httpResponse.Content != null)
            {
                foreach (KeyValuePair <string, IEnumerable <string> > header in httpResponse.Content.Headers)
                {
                    responseHeaders.Add(header.Key, header.Value.First());
                }

                responseStream = await httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false);
            }

            return((int)httpResponse.StatusCode, responseHeaders, responseStream);
        }
Beispiel #13
0
        public async Task ThrowArgumentExceptionGivenAuthorizationHeaderAddedByName()
        {
            // Arrange
            var request = new HttpRequestMessage(HttpMethod.Get, "https://github.com/FantasticFiasco");

            request.AddHeader(HeaderKeys.AuthorizationHeader, "some value");

            // Act
            var actual = Signer.SignAsync(
                httpClient,
                request,
                context.UtcNow,
                context.RegionName,
                context.ServiceName,
                context.Credentials);

            // Assert
            await actual.ShouldThrowAsync <ArgumentException>();
        }
Beispiel #14
0
        public async Task ThrowArgumentExceptionGivenXAmzDateHeaderAsync()
        {
            // Arrange
            var request = new HttpRequestMessage(HttpMethod.Get, "https://github.com/FantasticFiasco");

            request.AddHeader(HeaderKeys.XAmzDateHeader, "some value");

            // Act
            var actual = Signer.SignAsync(
                request,
                httpClient.BaseAddress,
                httpClient.DefaultRequestHeaders,
                context.UtcNow,
                context.RegionName,
                context.ServiceName,
                context.Credentials);

            // Assert
            await actual.ShouldThrowAsync <ArgumentException>();
        }
Beispiel #15
0
        public void ThrowArgumentExceptionGivenAuthorizationHeaderAddedByName()
        {
            // Arrange
            var request = new HttpRequestMessage(HttpMethod.Get, "https://github.com/FantasticFiasco");

            request.AddHeader(HeaderKeys.AuthorizationHeader, "some value");

            // Act
            Action actual = () => Signer.Sign(
                request,
                httpClient.BaseAddress,
                httpClient.DefaultRequestHeaders,
                context.UtcNow,
                context.RegionName,
                context.ServiceName,
                context.Credentials);

            // Assert
            actual.ShouldThrow <ArgumentException>();
        }
Beispiel #16
0
 /// <summary>
 /// 添加请求头
 /// </summary>
 /// <param name="request"></param>
 /// <param name="key"></param>
 /// <param name="value"></param>
 /// <returns></returns>
 public static HttpRequestMessage AddHeader(this HttpRequestMessage request, string key, string value)
 {
     return(request.AddHeader(key, new string[] { value }));
 }
    public async Task <(int statusCode, IDictionary <string, string> headers, Stream?responseStream)> SendRequestAsync(HttpMethodType method, string url, IReadOnlyDictionary <string, string>?headers = null, Stream?dataStream = null, CancellationToken cancellationToken = default)
    {
        HttpResponseMessage httpResponse;

        using (HttpRequestMessage httpRequest = new HttpRequestMessage(ConvertToMethod(method), url))
        {
            if (_config.HttpVersion == HttpVersion.Http1)
            {
                httpRequest.Version = _httpVersion1;
            }
            else if (_config.HttpVersion == HttpVersion.Http2)
            {
                httpRequest.Version = _httpVersion2;
            }
            else if (_config.HttpVersion == HttpVersion.Http3)
            {
                httpRequest.Version = _httpVersion3;
            }
            else if (_config.HttpVersion == HttpVersion.Unknown)
            {
                //Do nothing. Use default.
            }
            else
            {
                throw new ArgumentOutOfRangeException();
            }

            if (dataStream != null)
            {
                httpRequest.Content = new StreamContent(dataStream);
            }

            if (headers != null)
            {
                //Map all the headers to the HTTP request headers. We have to do this after setting the content as some headers are related to content
                foreach (KeyValuePair <string, string> item in headers)
                {
                    httpRequest.AddHeader(item.Key, item.Value);
                }
            }

            _logger.LogTrace("Sending HTTP request");

            HttpClient client = _clientFactory.CreateClient(_config.HttpClientName);
            httpResponse = await client.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
        }

        _logger.LogDebug("Got an {status} response with {Code}", httpResponse.IsSuccessStatusCode ? "successful" : "unsuccessful", httpResponse.StatusCode);

        IDictionary <string, string> responseHeaders = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

        foreach (KeyValuePair <string, IEnumerable <string> > header in httpResponse.Headers)
        {
            responseHeaders.Add(header.Key, header.Value.First());
        }

        Stream?contentStream = null;

        if (httpResponse.Content != null)
        {
            foreach (KeyValuePair <string, IEnumerable <string> > header in httpResponse.Content.Headers)
            {
                responseHeaders.Add(header.Key, header.Value.First());
            }

            contentStream = await httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false);
        }

        return((int)httpResponse.StatusCode, responseHeaders, contentStream);
    }
        public static async Task <Result> SignAsync(
            HttpClient httpClient,
            HttpRequestMessage request,
            DateTime now,
            string regionName,
            string serviceName,
            ImmutableCredentials credentials)
        {
            if (httpClient == null)
            {
                throw new ArgumentNullException(nameof(httpClient));
            }
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            if (request.Headers.Contains(HeaderKeys.XAmzDateHeader))
            {
                throw new ArgumentException(ErrorMessages.XAmzDateHeaderExists, nameof(request));
            }
            if (request.Headers.Authorization != null)
            {
                throw new ArgumentException(ErrorMessages.AuthorizationHeaderExists, nameof(request));
            }
            if (request.Headers.Contains(HeaderKeys.AuthorizationHeader))
            {
                throw new ArgumentException(ErrorMessages.AuthorizationHeaderExists, nameof(request));
            }
            if (regionName == null)
            {
                throw new ArgumentNullException(nameof(regionName));
            }
            if (serviceName == null)
            {
                throw new ArgumentNullException(nameof(serviceName));
            }
            if (serviceName == "s3")
            {
                throw new NotSupportedException(ErrorMessages.S3NotSupported);
            }
            if (credentials == null)
            {
                throw new ArgumentNullException(nameof(credentials));
            }

            UpdateRequestUri(httpClient, request);

            // Add required headers
            request.AddHeader(HeaderKeys.XAmzDateHeader, now.ToIso8601BasicDateTime());

            // Add conditional headers
            request.AddHeaderIf(credentials.UseToken, HeaderKeys.XAmzSecurityTokenHeader, credentials.Token);
            request.AddHeaderIf(!request.Headers.Contains(HeaderKeys.HostHeader), HeaderKeys.HostHeader, request.RequestUri.Host);

            // Build the canonical request
            var(canonicalRequest, signedHeaders) = await CanonicalRequest.BuildAsync(request, httpClient.DefaultRequestHeaders);

            // Build the string to sign
            var(stringToSign, credentialScope) = StringToSign.Build(
                now,
                regionName,
                serviceName,
                canonicalRequest);

            // Build the authorization header
            var authorizationHeader = AuthorizationHeader.Build(
                now,
                regionName,
                serviceName,
                credentials,
                signedHeaders,
                credentialScope,
                stringToSign);

            // Add the authorization header
            request.Headers.TryAddWithoutValidation(HeaderKeys.AuthorizationHeader, authorizationHeader);

            return(new Result(canonicalRequest, stringToSign, authorizationHeader));
        }
		private void AddRequestHeaders(HttpRequestMessage request)
		{
			foreach (string requestHeaderKey in requestHeaders.Keys)
			{
				request.AddHeader(requestHeaderKey, requestHeaders.Get(requestHeaderKey).ToString
					());
			}
		}
 protected internal virtual void AddRequestHeaders(HttpRequestMessage request)
 {
     foreach (string requestHeaderKey in requestHeaders.Keys)
     {
         request.AddHeader(requestHeaderKey, requestHeaders.Get(requestHeaderKey).ToString
             ());
     }
 }