Dear all,
I am writing to seek help, in how do I construct a method/or class that will allow me to login using the details from the db instead of written in code.
namespace API
{
public class DummyPrincipalProvider : IProvidePrincipal
{
private const string Username = "###";
private const string Password = "####";
public IPrincipal CreatePrincipal(string username, string password)
{
if (username != Username || password != Password)
{
return null;
}
var identity = new GenericIdentity(Username);
IPrincipal principal = new GenericPrincipal(identity, new[] { "trial" });
return principal;
}
}
}
namespace API
{
using System;
using System.Collections.Generic;
public partial class api_login
{
public string ID { get; set; }
public string username { get; set; }
public string password { get; set; }
public string description { get; set; }
public string role { get; set; }
}
}
Updated code
namespace API
{
public class BasicAuthMessageHandler : DelegatingHandler
{
private const string BasicAuthResponseHeader = "WWW-Authenticate";
private const string BasicAuthResponseHeaderValue = "Basic";
public IProvidePrincipal PrincipalProvider { get; set; }
protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
AuthenticationHeaderValue authValue = request.Headers.Authorization;
if (authValue != null && !String.IsNullOrWhiteSpace(authValue.Parameter))
{
api_login parsedCredentials = ParseAuthorizationHeader(authValue.Parameter);
if (parsedCredentials != null)
{
Thread.CurrentPrincipal = PrincipalProvider
.CreatePrincipal(parsedCredentials.username, parsedCredentials.password);
}
}
return base.SendAsync(request, cancellationToken)
.ContinueWith(task =>
{
var response = task.Result;
if (response.StatusCode == HttpStatusCode.Unauthorized
&& !response.Headers.Contains(BasicAuthResponseHeader))
{
response.Headers.Add(BasicAuthResponseHeader
, BasicAuthResponseHeaderValue);
}
return response;
});
}
private api_login ParseAuthorizationHeader(string authHeader)
{
string[] credentials = Encoding.ASCII.GetString(Convert
.FromBase64String(authHeader))
.Split(
new[] { ':' });
if (credentials.Length != 2 || string.IsNullOrEmpty(credentials[0])
|| string.IsNullOrEmpty(credentials[1]))
return null;
return new api_login()
{
username = credentials[0],
password = credentials[1],
};
}
}
}
Any help would be very much appreciated.
Many thanks for your time and help.