This article covers how to implement custom authentication for Piranha. To read about the different claims used in Piranha for Authorization, please refer to the article about Authentication in the section Architecture.
The manager interface uses the currently registered ISecurity
service to authenticate users when logging in. It is a simple interface with the following methods defined.
public interface ISecurity
{
/// <summary>
/// Authenticates the given credentials without
/// signing in the user.
/// </summary>
bool Authenticate(string username, string password);
/// <summary>
/// Authenticates and signs in the user with the
/// given credentials.
/// </summary>
Task<bool> SignIn(object context, string username, string password);
/// <summary>
/// Signs out the current user.
/// </summary>
Task SignOut(object context);
}
The registered security provider is responsible for adding the correct claims for the user. Let's as an example see how the development service Piranha.AspNetCore.SimpleSecurity
handles authentication.
public async Task<bool> SignIn(object context, string username, string password)
{
if (context is HttpContext)
{
if (Authenticate(username, password))
{
var user = Users
.Single(u => u.UserName == username && u.Password == password);
var claims = new List<Claim>();
foreach (var claim in user.Claims)
{
claims.Add(new Claim(claim, claim));
}
claims.Add(new Claim(ClaimTypes.Name, user.UserName));
claims.Add(new Claim(ClaimTypes.Sid, user.Id));
var identity = new ClaimsIdentity(claims, user.Password);
var principle = new ClaimsPrincipal(identity);
await ((HttpContext)context)
.SignInAsync("Piranha.SimpleSecurity", principle);
return true;
}
return false;
}
throw new ArgumentException("SimpleSecurity only works with a HttpContext");
}
Once you have implemented your custom login service for ISecurity you can simply register in in ConfigureServices
.
services.AddSingleton<Piranha.ISecurity, MyCustomAuthService>();