Skip to content

Authentication Support

adrianknight89 edited this page Jun 17, 2019 · 11 revisions

Cookies

Cookies are not enabled by default. If you want to enable them, use custom config:

ImageService.Instance.Initialize(new Configuration
{
	HttpClient = new HttpClient(new HttpClientHandler() 
	{
		AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate, 
		CookieContainer = new CookieContainer(),
		UseCookies = true
	})
});

Custom authentication / headers

If your web server or API requires 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 request:

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 " + _getToken.Invoke());
            return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
        }
    }
}