public class Startup
{
public void Configuration(IAppBuilder appBuilder)
{
appBuilder.UseCustomAuthentication();
}
}
public class CustomAuthenticationOptions : AuthenticationOptions
{
public CustomAuthenticationOptions(string authenticationType) : base(authenticationType)
{
}
public int MyProperty { get; set; }
}
protected override async Task<AuthenticationTicket> AuthenticateCoreAsync()
{
//user validation task
//ClientCertificateValidationResult validationResult = await Task<ClientCertificateValidationResult>.Run(() => ValidateCertificate(Request.Environment));
bool validation = true;
if (validation)
{
AuthenticationProperties authProperties = new AuthenticationProperties();
authProperties.IssuedUtc = DateTime.UtcNow;
authProperties.ExpiresUtc = DateTime.UtcNow.AddDays(1);
authProperties.AllowRefresh = true;
authProperties.IsPersistent = true;
//user claims
IList<Claim> claimCollection = new List<Claim>
{
new Claim(ClaimTypes.Name, "Andras")
, new Claim(ClaimTypes.Country, "Sweden")
, new Claim(ClaimTypes.Gender, "M")
, new Claim(ClaimTypes.Surname, "Nemes")
, new Claim(ClaimTypes.Email, "hello@me.com")
, new Claim(ClaimTypes.Role, "IT")
, new Claim("HasValidClientCertificate", "true")
};
ClaimsIdentity claimsIdentity = new ClaimsIdentity(claimCollection, "myCustomType");
AuthenticationTicket ticket = new AuthenticationTicket(claimsIdentity, authProperties);
return ticket;
}
return await Task.FromResult<AuthenticationTicket>(null);
}
//this is ran awaitable from able by the invoke, I could use this to get the users claims
//private ClientCertificateValidationResult ValidateCertificate(IDictionary<string, object> owinEnvironment)
//{
// if (owinEnvironment.ContainsKey(_owinClientCertKey))
// {
// X509Certificate2 clientCert = Context.Get<X509Certificate2>(_owinClientCertKey);
// return _clientCertificateValidator.Validate(clientCert);
// }
// ClientCertificateValidationResult invalid = new ClientCertificateValidationResult(false);
// invalid.AddValidationException("There's no client certificate attached to the request.");
// return invalid;
//}
}
public static class CustomAuthenticationExtension
{
public static void UseCustomAuthentication(this IAppBuilder appBuilder)
{
appBuilder.Use<CustomAuthMiddleware>(new CustomAuthenticationOptions("CustomAuthenticationType"));
}
}
public class CustomAuthMiddleware : AuthenticationMiddleware<CustomAuthenticationOptions>
{
public CustomAuthMiddleware(OwinMiddleware next, CustomAuthenticationOptions options) : base(next, options)
{
}
protected override AuthenticationHandler<CustomAuthenticationOptions> CreateHandler()
{
return new CustomAuthenticationHandler();
}
}