-
Notifications
You must be signed in to change notification settings - Fork 376
Authentication Support
Daniel Luberda edited this page May 28, 2019
·
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> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
request.Headers.Add("Authorization", "Bearer " + _getToken.Invoke());
return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
}
}
}
Cookies are not enabled by default. If you want to enable it use custom config:
ImageService.Instance.Initialize(new Configuration
{
HttpClient = new HttpClient(new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
CookieContainer = new CookieContainer(),
UseCookies = true
})
});