From 5ce415c12d14239a9fa6087b5da2842f534bb8f6 Mon Sep 17 00:00:00 2001 From: Ali Servet Donmez Date: Fri, 7 Apr 2017 11:39:32 +0200 Subject: [PATCH] Adds support for "basic" authentication with URL credentials --- src/Dispatch.Api.Client.Tests/UnitTest1.cs | 22 ++++++++++++++++++++++ src/Messaging/Http/HttpRequestSender.cs | 19 ++++++++++++++++--- 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/src/Dispatch.Api.Client.Tests/UnitTest1.cs b/src/Dispatch.Api.Client.Tests/UnitTest1.cs index ddea05f..f6935e2 100644 --- a/src/Dispatch.Api.Client.Tests/UnitTest1.cs +++ b/src/Dispatch.Api.Client.Tests/UnitTest1.cs @@ -64,6 +64,23 @@ public async Task Test_Delete() Assert.True(result); } + [Fact] + [UsedImplicitly] + public async Task Test_BasicAuth() + { + var schedule = new DateTimeOffset(DateTime.Now); + + var request = new ScheduledBundleRequest(schedule); + + request.HttpRequests.Add(NewHttpRequestMessageWithBasicAuth()); + + var response = await this.client.ScheduleAsync(request) + .ConfigureAwait(false); + + Assert.NotNull(response.Id); + Assert.Equal(schedule, response.Schedule); + } + [Fact] [UsedImplicitly] public async Task Test_MailAttachments() @@ -127,6 +144,11 @@ private static HttpRequestMessage NewHttpRequestMessage() return new HttpRequestMessage("HEAD", "http://requestb.in/188o2xj1"); } + private static HttpRequestMessage NewHttpRequestMessageWithBasicAuth() + { + return new HttpRequestMessage("HEAD", "http://user:pass@requestb.in/1lq1vzu1"); + } + private static ApexnetPushNotification NewApexnetPushNotification() { const string AuthKey = "3892DB2C-53A9-4B57-9638-08C1E91319C8"; diff --git a/src/Messaging/Http/HttpRequestSender.cs b/src/Messaging/Http/HttpRequestSender.cs index 5878201..e8ec53c 100644 --- a/src/Messaging/Http/HttpRequestSender.cs +++ b/src/Messaging/Http/HttpRequestSender.cs @@ -3,6 +3,8 @@ namespace Apexnet.Messaging.Http using System; using System.Collections.Generic; using System.Net.Http; + using System.Net.Http.Headers; + using System.Text; public class HttpRequestSender : IDisposable { @@ -33,10 +35,21 @@ private HttpRequestSender(HttpClient smtpClient) public void Send(HttpRequestMessage message) { - var httpRequestMessage = new System.Net.Http.HttpRequestMessage( - HttpMethodsMapping[message.Method.ToUpperInvariant()], - message.RequestUri); + var requestUri = new Uri(message.RequestUri); + var httpRequestMessage = + new System.Net.Http.HttpRequestMessage( + HttpMethodsMapping[message.Method.ToUpperInvariant()], + requestUri); + + if (!string.IsNullOrWhiteSpace(requestUri.UserInfo)) + { + httpRequestMessage.Headers.Authorization = new AuthenticationHeaderValue( + "Basic", + Convert.ToBase64String(Encoding.UTF8.GetBytes(requestUri.UserInfo))); + } + + // This will wait Taks to complete, but we won't know if the request "succeeded" or "failed". this.httpClient.SendAsync(httpRequestMessage) .Wait(); }