Membership

The membership is service layer there is one middle layer between the web application and the data repositories. This layer only for the membership’s requirements leaving all data repositories being injected as they are directly to API Controllers.

First, we’ll create a simple encryption service to create salts and encrypted passwords and then we’ll use this service to implement a custom membership.

IEncryptionService.cs

public interface IEncryptionService 
{ 
  string CreateSalt(); 
  string EncryptPassword(string password, string salt); 
}

IMembershipService.cs

public interface IEncryptionService 
public interface IMembershipService 
{ 
  MembershipContext ValidateUser(string username, string password); 
  User CreateUser(string username, string email, string password, int[] roles); 
  User GetUser(int userId); 
  List<Role> GetUserRoles(string username); 
}

Add the encryption service implementation. It’s simple password encryption based on a salt and the SHA256 algorithm from System.Security.Cryptography namespace.

public class EncryptionService : IEncryptionService
{
	public string CreateSalt()
	{
		var data = new byte[0x10];
		using (var cryptoServiceProvider = new RNGCryptoServiceProvider())
		{
			cryptoServiceProvider.GetBytes(data);
			return Convert.ToBase64String(data);
		}
	}

	public string EncryptPassword(string password, string salt)
	{
		using (var sha256 = SHA256.Create())
		{
			var saltedPassword = string.Format("{0}{1}", salt, password);
			byte[] saltedPasswordAsBytes = Encoding.UTF8.GetBytes(saltedPassword);
			return Convert.ToBase64String(sha256.ComputeHash(saltedPasswordAsBytes));
		}
	}
}

MembershipService.cs

public class MembershipService : IMembershipService
{
	#region Variables
	private readonly IEntityBaseRepository<User> _userRepository;
	private readonly IEntityBaseRepository<Role> _roleRepository;
	private readonly IEntityBaseRepository<UserRole> _userRoleRepository;
	private readonly IEncryptionService _encryptionService;
	private readonly IUnitOfWork _unitOfWork;
	#endregion
	public MembershipService(IEntityBaseRepository<User> userRepository, IEntityBaseRepository<Role> roleRepository,
	IEntityBaseRepository<UserRole> userRoleRepository, IEncryptionService encryptionService, IUnitOfWork unitOfWork)
	{
		_userRepository = userRepository;
		_roleRepository = roleRepository;
		_userRoleRepository = userRoleRepository;
		_encryptionService = encryptionService;
		_unitOfWork = unitOfWork;
	}
	
}