2.3: Adding Auth Service

Add Authentication Interface

Add an interface to your .Contracts project by right clicking on the folder name and selecting "New C# Interface" called IAuthService.cs.

Add method signatures for register, login, and checking whether the user already exists in the database.

using System.Threading.Tasks;
using EFConnect.Data.Entities;

namespace EFConnect.Contracts
{
    public interface IAuthService
    {
         Task<User> Register(User user, string password);
         Task<User> Login(string username, string password);
         Task<bool> UserExists(string username);
    }
}

Add Concrete AuthService

In the .Services project - create a new C# class called AuthService.cs that implements IAuthService.

Start by adding a constructor to inject our DbContext:

Ctrl + . on the context parameter and choose Generate field from parameter.

Now, ctrl + . on IAuthRepository and select Implement interface

Add CreatePasswordHash Method

We'll add a private method below the public methods to create a password hash.

It will take three parameters: one will be passed by value: password, and two will be passed by reference: passwordHash and passwordSalt - this will allow our method to directly alter the values held by the passwordHash and passwordSalt variables.

Implement Register Method

Now that we have a method to create our salted hash, we can implement our register method.

Add VerifyPasswordHash Method

Next, we need another private helper method to check the password a user enters against the hashed password saved to the database in order to implement our Login() method.

This method will work in the opposite direction of our CreatePasswordHash() method.

We'll loop through the computed hash and compare each byte against what's stored in our database. If anything doesn't match, we'll return false - otherwise, we'll return true.

Implement Login Method

In this method, we need to compare what's stored in our database to what is entered by the user using our VerifyPasswordHash() method.

Implement UserExists() method

Last updated