Two Factor Authentication
In the 1st post of this section, I showed you the controllers and models that I had created for this project. This post carries on from that post and I show you the code for passing data and retrieving data from the database using ADO.Net.
The Web.Domain layer has three classes, one for creating the user, one for retrieving user data and the third is class has a static method that only contains the connection string details from the web.config file.
The reason I create this class is so that I only need to change the code in one place and all other classes using it will use the new connection details.
The create user account class inserts the user details into the database, the method is void, and I use a try-catch block to handle any errors. In this case, the stored procedure checks if the username already exists. This can be done in the UI, but for this example, I'm doing the check-in via a stored procedure.
The interface is in a separate class, but I have added the code within the same code block below.
The profile class returns the user details, as I have a reference to my model layer, I need to pass in the model for the parameters saving any possible typos.
As you can see, I'm also calling the stored procedure with the async keyword to make an asynchronous call to the database. This could also have been done on the create user account class, but I wanted to show both ways.
Again I have added the interface in the code block below, but this is actually in its own class.
You can see the Encrypt data class below; this class uses Effortless.Net.Encryptiona Nuget package which you can install.
You can also see that the location of the encryption key is retrieved from the web.config file. The actual location of the file is outside the web application for security reasons.
I'm also using a Tuple for returning the key and encrypted data. I could have used out parameters, but for this example, I thought Tuples would be a better option.
Finally, I'm using Windows built-in encryption ProtectedData as another alternative to encrypting data.
The validate login class uses the built-in Owen claims and Microsoft.ASPNet.Identity.IPasswordHasher, this class hashes the user password and verifies the password for logins.
The claims cookie is only created if the password supplied by the user matches, if not no claims are created.
The security stamp class is a simple static class that takes UTC date time and the user ID, this is stored in the database and would be used to compare the current data time against the UTC time when the user verifies their email address. If they check their email after one day, then verification will fail.
In this post, I carried on from the last blog and showed you the code for the encryption class, user profile and creating account classes and the password hash class. In the final post, I will show you how it all fits together.
If you have any questions on this post, please use the form below.