Authentication

Last Updated: 2018-12-22

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 under the section Components.

The manager interface uses the currently registered ISecurity provider to authenticate users when logging. It is a simple interface with the following methods defined.

ISecurity Interface

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);
}

Example Authentication

The registered security provider is responsible for adding the correct claims for the user. Let's as an example see how the development provider Piranha.AspNetCore.SimpleSecurity provider handles login.

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");
}


Registering Authentication

Once you have implemented your custom login service for ISecurity you can simply register in in ConfigureServices.

services.AddSingleton<Piranha.ISecurity, MyCustomAuthService>();