3 Comments
  •   Posted in: 
  • UWP

Using Basic Authentication in a WinRT app is a common requirement. The basic authentication isn’t supported out-of-the box by the HttpClient  but the HttpClient class has a good extensibility model: The basic authentication can be implemented using a custom DelegatingHandler:

    public class BasicAuthHandler : DelegatingHandler
    {
        private readonly string username;
        private readonly string password;

        public BasicAuthHandler(string username, string password)
            : this(username, password, new HttpClientHandler())
        {
        }

        public BasicAuthHandler(string username, string password, HttpMessageHandler innerHandler)
            : base(innerHandler)
        {
            this.username = username;
            this.password = password;
        }

        protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            request.Headers.Authorization = CreateBasicHeader();

            var response = await base.SendAsync(request, cancellationToken);

            return response;
        }

        public AuthenticationHeaderValue CreateBasicHeader()
        {
            var byteArray = System.Text.Encoding.UTF8.GetBytes(username + ":" + password);
            var base64String = Convert.ToBase64String(byteArray);
            return new AuthenticationHeaderValue("Basic", base64String);
        }
    }

The BasicAuthHandler can be used by passing it into the HttpClient’s constructor:

            var client = new HttpClient(new BasicAuthHandler("username", "password"));

            var data = await client.GetStringAsync("http://secured.address.com/api");