Skip to content

Authentication Support

Fabien Molinet edited this page May 16, 2016 · 11 revisions

If your web server, or API, requires an authentication you can give it using a custom HttpClient. When your application starts add a call to Initialize (for example in AppDelegate or MainActivity):

ImageService.Instance.Initialize(new Configuration
{
	HttpClient = new HttpClient(new AuthenticatedHttpImageClientHandler(_authService.GetToken))
});
namespace MyNamespace
{
    public class AuthenticatedHttpImageClientHandler : HttpClientHandler
    {
        private readonly Func<Task<string>> _getToken;`

        public AuthenticatedHttpImageClientHandler(Func<Task<string>> getToken)
        {
            if (getToken == null) throw new ArgumentNullException("getToken");
            _getToken = getToken;
        }

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            request.Headers.Add("Authorization", "Bearer " + token);
            return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
        }
    }
}