protected async Task <HttpResponseMessage> SendRequest(Action <AppSendBuilder> configure)
        {
            var request = new HttpRequestMessage(HttpMethod.Get, _client.HttpClient.BaseAddress);
            var builder = new AppSendBuilder(request);

            configure(builder);

            var response = await _client.SendAsync(request);

            var expectedStatus = request.GetExpectedStatus();

            if (expectedStatus.HasValue && expectedStatus.Value != response.StatusCode)
            {
                string content = await response.Content.ReadAsStringAsync();

                if (content.Length > 1000)
                {
                    content = content.Substring(0, 1000);
                }

                throw new HttpRequestException($"Expected status code {expectedStatus.Value} but received status code {response.StatusCode} ({response.ReasonPhrase}).\n" + content);
            }

            return(response);
        }
Example #2
0
        protected Task <FluentResponse> SendRequest(Action <SendBuilder> configure)
        {
            var request = _client.CreateRequest();
            var builder = new SendBuilder(request);

            configure(builder);

            if (request.ContentData != null && !(request.ContentData is HttpContent))
            {
                string mediaType = !String.IsNullOrEmpty(request.ContentType) ? request.ContentType : "application/json";
                request.ContentData = new StringContent(_serializer.SerializeToString(request.ContentData), Encoding.UTF8, mediaType);
            }

            return(_client.SendAsync(request));
        }
Example #3
0
        protected Task <FluentResponse> SendRequest(Action <SendBuilder> configure)
        {
            var request = _client.CreateRequest();
            var builder = new SendBuilder(request);

            configure(builder);

            if (request.ContentData != null && request.ContentData.GetType() != typeof(string))
            {
                request.ContentData = _serializer.SerializeToString(request.ContentData);
                if (!String.IsNullOrEmpty(request.ContentType))
                {
                    request.ContentType = "application/json";
                }
            }

            return(_client.SendAsync(request));
        }
Example #4
0
        public async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, Route = "Proxy/{*path}")] HttpRequest req, string path)
        {
            var authHeader   = req.Headers["Authorization"].ToString();
            var clientId     = "";
            var clientSecret = "";

            var queryString = HttpUtility.ParseQueryString(req.QueryString.Value);

            if (authHeader.StartsWith("basic", StringComparison.OrdinalIgnoreCase))
            {
                // parse client credentials
                var credentialString = Encoding.UTF8.GetString(Convert.FromBase64String(authHeader.Substring("Basic ".Length).Trim()));
                var credentials      = credentialString.Split(':');

                if (credentials.Length != 2)
                {
                    return(new HttpResponseMessage(HttpStatusCode.BadRequest)
                    {
                        Content = new StringContent("Incorrect Basic authentication header format.")
                    });
                }
                clientId     = credentials[0];
                clientSecret = credentials[1];
            }
            else if (req.Query.ContainsKey("$clientid") && req.Query.ContainsKey("$clientSecret"))
            {
                req.Query.TryGetValue("$clientId", out var id);
                req.Query.TryGetValue("$clientSecret", out var secret);

                clientId     = id[0];
                clientSecret = secret[0];

                queryString.Remove("$clientId");
                queryString.Remove("$clientSecret");
            }
            else
            {
                return(new HttpResponseMessage(HttpStatusCode.Unauthorized)
                {
                    Content = new StringContent("Specify client credentials either as Basic auth or in Query.")
                });
            }
            try
            {
                // acquire bearer token
                var token = await _tokenService.GetToken(clientId, clientSecret);

                // send request with previously acquired bearer token
                var client = new FluentClient(new Uri(_options.Value.BaseUrl), _factory.CreateClient());

                var builder = new UriBuilder(_options.Value.BaseUrl)
                {
                    Path  = path,
                    Query = queryString.ToString(),
                    Port  = -1
                };
                var resource = builder.ToString();

                var message = new HttpRequestMessage(new HttpMethod(req.Method), resource);
                message.Content = new StreamContent(req.Body);
                foreach (var header in req.Headers)
                {
                    if (!message.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray()))
                    {
                        message.Content.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray());
                    }
                }
                message.Headers.Host = builder.Host;

                //send request with previously acquired bearer token
                return(await client.SendAsync(message)
                       .WithBearerAuthentication(token)
                       .AsMessage());
            }
            catch (ApiException ex)
            {
                // Forward any API error
                return(ex.Response.Message);
            }
        }