Building Web Application Using Entity Framework And MVC 5: Part 2

This article is a continuation of my previous article about “Building Web Application Using Entity Framework And MVC 5: Part 1”.

This article explains the following:

  • Creating a Login page that would validate and authenticate the user using Forms Authentication
  • Creating a custom role-based page authorization using a custom Authorize filter

For this specific demo I will show how to create a simple Login form by implementing a custom authentication and role-based page authorization without using ASP.NET Membership or ASP.NET Identity. If you want to build an app that allows users to login using their social media accounts like Facebook, Twitter, Google Plus and so on then you may want explore ASP.NET Identity instead.

Note that I will not elaborate more on the details about the model, view and controllers function so before proceeding further, I'd suggest you to check my previous article “Building Web Application Using Entity Framework And MVC 5: Part 1” first, especially if you are new to ASP.NET MVC web development.

Before we get our hands dirty let's talk about a bit of security in general.

Forms Authentication Overview

Security is an integral part of any Web-based application. The majority of web sites currently heavily rely on authentication and authorization for securing their application. You can think of a web site as somewhat analogous to a company office where an office is open for people like applicants or messengers to come, but there are certain parts of the facility, such as workstations and conference rooms, that are accessible only to people, such as employees, with certain credentials. An example is when a you build a shopping cart application that accepts user's credit card information for payment purposes and stores them into your database. ASP.NET helps protect your database from public access by providing authentication and authorization.

Forms authentication lets you authenticate users using your own code and then maintain an authentication token in a cookie or in the page URL. To use forms authentication, you create a login page that collects credentials from the user that includes code to authenticate the credentials. Typically you configure the application to redirect requests to the login page when users try to access a protected resource, such as a page that requires authentication. If the user's credentials are valid, you can call methods of the FormsAuthentication class to redirect the request back to the originally requested resource with an appropriate authentication ticket (cookie).

Let’s get our hands dirty!

As a recap, here's the previous project structure below:

Implementing the Login Page

STEP 1: Enabling Forms Authentication

To allow forms authentication, the very first thing to do in your application is to configure FormsAuthentication that manages forms authentication services to your web application. The default authentication mode for ASP.NET is “Windows”. To enable forms authentication, add the <authentication> and <forms> elements under the <system.web> element in your web.config as in the following:

  1. <system.web>  
  2.     <authentication mode="Forms">  
  3.       <forms loginUrl="~/Account/Login" defaultUrl="~/Home/Welcome"></forms>  
  4.     </authentication>  
  5. </system.web>  

Setting the loginUrl enables the application to determine where to redirect an unauthenticated user who attempts to access a secured page. The defaultUrl redirects users to the specified page after successful log-in.

STEP 2: Adding the UserLoginView Model

Let's go ahead and create a model view class for our Login page by adding the following code within the “UserModel” class:

  1. public class UserLoginView  
  2. {  
  3.     [Key]  
  4.     public int SYSUserID { getset; }  
  5.     [Required(ErrorMessage = "*")]  
  6.     [Display(Name = "Login ID")]  
  7.     public string LoginName { getset; }  
  8.     [Required(ErrorMessage = "*")]  
  9.     [DataType(DataType.Password)]  
  10.     [Display(Name = "Password")]  
  11.     public string Password { getset; }  
  12. }  

The fields defined above will be used in our Login page. You may also see that the fields are decorated with Required, Display and DataType attributes. These attributes are called Data Annotations.

STEP 3: Adding the GetUserPassword() Method

Add the following code for the “UserManager.cs” class:

  1. public string GetUserPassword(string loginName) {  
  2.             using (DemoDBEntities db = new DemoDBEntities()) {  
  3.                 var user = db.SYSUsers.Where(o => o.LoginName.ToLower().Equals(loginName));  
  4.                 if (user.Any())  
  5.                     return user.FirstOrDefault().PasswordEncryptedText;  
  6.                 else  
  7.                     return string.Empty;  
  8.             }  
  9. }  

As the method name suggests, it gets the corresponding password from the database for a specific login name using a LINQ query.

STEP 4: Adding the Login Action Method

Add the following code for the “AccountController” class:

  1. public ActionResult LogIn() {  
  2.             return View();  
  3.  }  
  5.  [HttpPost]  
  6.  public ActionResult LogIn(UserLoginView ULV, string returnUrl) {  
  7.             if (ModelState.IsValid) {  
  8.                 UserManager UM = new UserManager();  
  9.                 string password = UM.GetUserPassword(ULV.LoginName);  
  11.                 if (string.IsNullOrEmpty(password))  
  12.                     ModelState.AddModelError("""The user login or password provided is incorrect.");  
  13.                 else {  
  14.                     if (ULV.Password.Equals(password)) {  
  15.                         FormsAuthentication.SetAuthCookie(ULV.LoginName, false);  
  16.                         return RedirectToAction("Welcome""Home");  
  17.                     }  
  18.                     else {  
  19.                         ModelState.AddModelError("""The password provided is incorrect.");  
  20.                     }  
  21.                 }  
  22.             }  
  24.             // If we got this far, something failed, redisplay form  
  25.             return View(ULV);  
  26. }  

As you can see, there are two methods above with the same name. The first one is the "Login" method that simply returns the LogIn.cshtml view. We will create this view in the next step. The second one is also named "Login" but it is decorated with the "[HttpPost]" attribute. This attribute specifies the overload of the "Login" method that can be invoked only for POST requests.

The second method will be triggered once the Button "LogIn" is fired. What it does is, first it will check if the required fields are supplied so it checks for ModelState.IsValid condition. It will then create an instance of the UserManager class and call the GetUserPassword() method by passing the user LoginName value supplied by the user. If the password returns an empty string then it will display an error to the view. If the password supplied is equal to the password retrieved from the database then it will redirect the user to the Welcome page, otherwise it will display an error stating that the login name or password supplied is invalid.

STEP 5: Adding the Login View

Before adding the view, be sure to build your application first to ensure that the application is error-free. After a successful build, navigate to the “AccountController” class and right-click on the Login action method and then select “Add View”. This will bring up the following dialog below:

Take note of the values supplied for each field. Now click on Add to let Visual Studio scaffold the UI for you. The is the modified HTML markup:

  1. @model MVC5RealWorld.Models.ViewModel.UserLoginView  
  3. @{  
  4.     ViewBag.Title = "LogIn";  
  5.     Layout = "~/Views/Shared/_Layout.cshtml";  
  6. }  
  8. <h2>LogIn</h2>  
  10. @using (Html.BeginForm())   
  11. {  
  12.     @Html.AntiForgeryToken()  
  14.     <div class="form-horizontal">  
  15.         <hr />  
  16.         @Html.ValidationSummary(true""new { @class = "text-danger" })  
  17.         <div class="form-group">  
  18.             @Html.LabelFor(model => model.LoginName, htmlAttributes: new { @class = "control-label col-md-2" })  
  19.             <div class="col-md-10">  
  20.                 @Html.EditorFor(model => model.LoginName, new { htmlAttributes = new { @class = "form-control" } })  
  21.                 @Html.ValidationMessageFor(model => model.LoginName, ""new { @class = "text-danger" })  
  22.             </div>  
  23.         </div>  
  25.         <div class="form-group">  
  26.             @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })  
  27.             <div class="col-md-10">  
  28.                 @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })  
  29.                 @Html.ValidationMessageFor(model => model.Password, ""new { @class = "text-danger" })  
  30.             </div>  
  31.         </div>  
  33.         <div class="form-group">  
  34.             <div class="col-md-offset-2 col-md-10">  
  35.                 <input type="submit" value="Login" class="btn btn-default" />  
  36.             </div>  
  37.         </div>  
  38.     </div>  
  39. }  
  41. <div>  
  42.     @Html.ActionLink("Back to Main""Index""Home")  
  43. </div>  

STEP 6: Implementing the Logout Functionality

The logout code is quiet simple. Just add the following method to the AccountController class.

  1. [Authorize]  
  2. public ActionResult SignOut() {  
  3.             FormsAuthentication.SignOut();  
  4.             return RedirectToAction("Index""Home");  
  5. }  

The FormsAuthentication.SignOut method removes the forms-authentication ticket from the browser. We then redirect the user to the Index page after signing out.

Here’s the corresponding action link for the Logout:

  1. @Html.ActionLink("Signout","SignOut","Account")  

STEP 7: Run the Application

Running your application should display something like the following.

When validation triggers:

After successful Logging in:

After logging out:

That was simple! Now let’s have a look at how to implement a simple role-based page authorization.

Implementing a Simple Role-Based Page Authorization

Authorization is a function that specifies access rights to a certain resource or page. One practical example is having a page that only a certain user role can have access to. For example, only allow an administrator to access the maintenance page for your application. In this section we will create a simple implementation on how to do that.

STEP 1: Creating the UserIsInRole Method

Add the following code to the "UserManager" class:

  1. public bool IsUserInRole(string loginName, string roleName) {  
  2.             using (DemoDBEntities db = new DemoDBEntities()) {  
  3.                 SYSUser SU = db.SYSUsers.Where(o => o.LoginName.ToLower().Equals(loginName))?.FirstOrDefault();  
  4.                 if (SU != null) {  
  5.                     var roles = from q in db.SYSUserRoles  
  6.                                 join r in db.LOOKUPRoles on q.LOOKUPRoleID equals r.LOOKUPRoleID  
  7.                                 where r.RoleName.Equals(roleName) && q.SYSUserID.Equals(SU.SYSUserID)  
  8.                                 select r.RoleName;  
  10.                     if (roles != null) {  
  11.                         return roles.Any();  
  12.                     }  
  13.                 }  
  15.                 return false;  
  16.             }  
  17. }  

The method above takes the loginName and roleName as parameters. What it does is it checks for the existing records in the user's table and then validates if the corresponding user has roles assigned to it.

STEP 2: Creating a Custom Authorization Attribute Filter

If you remember, we are using the [Authorize] attribute to restrict anonymous users from accessing a certain action method. The [Authorize] attribute provides filters for users and roles and it’s fairly easy to implement it if you are using a membership provider. Since we are using our own database for storing users and roles, we need to implement our own authorization filter by extending the AuthorizeAttribute class.

The AuthorizeAttribute specifies that access to a controller or action method is restricted to users who meet the authorization requirements. Our goal here is to allow page authorization based on user roles and nothing else. If you want to implement custom filters to do a certain task and value the separation of concerns then you may want to look at IAutenticationFilter instead.

To start, add a new folder and name it “Security”. Then add the “AuthorizeRoleAttribute” class. The following is a screen shot of the structure:

Here’s the code block for our custom filter:

  1. using System.Web;  
  2. using System.Web.Mvc;  
  3. using MVC5RealWorld.Models.DB;  
  4. using MVC5RealWorld.Models.EntityManager;  
  6. namespace MVC5RealWorld.Security  
  7. {  
  8.     public class AuthorizeRolesAttribute : AuthorizeAttribute  
  9.     {  
  10.         private readonly string[] userAssignedRoles;  
  11.         public AuthorizeRolesAttribute(params string[] roles) {  
  12.             this.userAssignedRoles = roles;  
  13.         }  
  14.         protected override bool AuthorizeCore(HttpContextBase httpContext) {  
  15.             bool authorize = false;  
  16.             using (DemoDBEntities db = new DemoDBEntities()) {  
  17.                 UserManager UM = new UserManager();  
  18.                 foreach (var roles in userAssignedRoles) {  
  19.                     authorize = UM.IsUserInRole(httpContext.User.Identity.Name, roles);  
  20.                     if (authorize)  
  21.                         return authorize;  
  22.                 }  
  23.             }  
  24.             return authorize;  
  25.         }  
  26.         protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) {  
  27.             filterContext.Result = new RedirectResult("~/Home/UnAuthorized");  
  28.         }  
  29.     }  
  30. }  

There are two main methods in the class above that we have overridden. The AuthorizeCore() method is the entry point for the authentication check. This is where we check the roles assigned for certain users and returns the result specifying whether or not the user is allowed to access a page. The HandleUnuathorizedRequest() is a method in which we redirect un-authorized users to a certain page.

STEP 3: Adding the AdminOnly and UnAuthorized page

Now switch back to “HomeController” and add the following code:

  1. [AuthorizeRoles("Admin")]  
  2. public ActionResult AdminOnly() {  
  3.        return View();  
  4. }  
  6. public ActionResult UnAuthorized() {  
  7.        return View();  
  8. }  

If you notice, we decorated the AdminOnly action with our custom authorization filter by passing the value of “Admin” as the role name. This means that only allow admin users have access to the AdminOnly page. To support multiple role access, just add another role name by separating it with a comma, for example [AuthorizeRoles(“Admin”,”Manager”)]. Note that the value of “Admin” and “Manager” should match the role names from your database. And finally, be sure to reference the namespace below before using the AuthorizeRoles attribute:

  1. using MVC5RealWorld.Security;  

Here’s the AdminOnly.cshtml view:

  1. @{  
  2.     ViewBag.Title = "AdminOnly";  
  3.     Layout = "~/Views/Shared/_Layout.cshtml";  
  4. }  
  6. <h2>For Admin users only!</h2>  
  7. And here’s the UnAuthorized.cshtml view:  
  8. @{  
  9.     ViewBag.Title = "UnAuthorized";  
  10.     Layout = "~/Views/Shared/_Layout.cshtml";  
  11. }  

And here’s the UnAuthorized.cshtml view:

  1. @{  
  2.     ViewBag.Title = "UnAuthorized";  
  3.     Layout = "~/Views/Shared/_Layout.cshtml";  
  4. }  
  6. <h2>Unauthorized Access!</h2>  
  7. <p>Oops! You don't have permission to access this page.</p>  
  9. <div>  
  10.     @Html.ActionLink("Back to Main""Welcome""Home")  
  11. </div>  

STEP 4: Testing the functionality

Before we test the functionality, lets add an admin user to the database first. For this demo I have inserted the following data to the database:

  1. INSERT INTO SYSUser (LoginName,PasswordEncryptedText, RowCreatedSYSUserID, RowModifiedSYSUserID)  
  2. VALUES ('Admin','Admin',1,1)  
  3. GO  
  4. INSERT INTO SYSUserProfile (SYSUserID,FirstName,LastName,Gender,RowCreatedSYSUserID, RowModifiedSYSUserID)  
  5. VALUES (2,'Vinz','Durano','M',1,1)  
  6. GO  
  8. INSERT INTO SYSUserRole (SYSUserID,LOOKUPRoleID,IsActive,RowCreatedSYSUserID, RowModifiedSYSUserID)  
  9. VALUES (2,1,1,1,1)  

Okay, now we have data to test and we are ready to run the application.

STEP 5: Run the Application

The following are some of the screenshots captured during my test.

When logging in as a normal user and accessing the following URL: http://localhost:15599/Home/AdminOnly

When logging in as an Admin user and accessing the following URL: http://localhost:15599/Home/AdminOnly

In my next article I will show how to do Edit, Update and Delete operations within our MVC application, so stay tuned.

That’s it! I hope you find this article useful.

Up Next
    Ebook Download
    View all
    View all