Skip to content

Authentication Support

Daniel Luberda edited this page Feb 10, 2017 · 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))
});

Now if you need a custom token be added to each requests:

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> GetAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            request.Headers.Add("Authorization", "Bearer " + token);
            return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
        }
    }
}