Authentication - Xablu/Xablu.WebApiClient GitHub Wiki
The WebApiClient is capable of doing (simple) authentication with something that looks like this:
public class AuthenticationClient : BaseClient, IAuthenticationClient
{
public AuthenticationClient(IWebApiClient apiClient) : base(apiClient)
{
}
public Task<int> AuthenticateWithCredentials(string username, string password)
{
var uri = new UriTemplate("user/logon");
var content = new MultipartFormDataContent();
content.Add(new StringContent(username), "username");
content.Add(new StringContent(password), "password");
return ExecuteRemoteRequest(async () => await apiClient.PostAsync<MultipartFormDataContent, int>(Priority.UserInitiated, uri.Resolve(), content).ConfigureAwait(false));
}
}
And of course you need a service that's capable of handling user logic something like this:
public class AuthenticationService : IAuthenticationService
{
private IBlobCache cache;
private IAuthenticationClient authClient;
public AuthenticationService(IAuthenticationClient authClient, IBlobCache cache = null)
: base()
{
this.cache = (cache ?? BlobCache.Secure);
this.authClient = authClient;
}
public async Task<bool> Login(string username, string password)
{
var userId = await authClient.AuthenticateWithCredentials(username, password).ConfigureAwait(false);
if (userId != default(int))
{
await this.cache.InsertObject(Settings.UserIdCacheKey, userId);
return true;
}
return false;
}
public async Task<bool> IsAuthenticated()
{
try
{
var userId = await cache.GetObject<int>(Settings.UserIdCacheKey).ToTask().ConfigureAwait(false);
return true;
}
catch (KeyNotFoundException)
{
return false;
}
}
public async Task Logout()
{
await cache.InvalidateAll().ToTask().ConfigureAwait(false);
}
}