Skip to main content

ASP.NET MVC Security System


ASP.NET MVC Security System (Authentication and Authorization)

In this post, we are going to be looking at security system in ASP.NET MVC Application, it will involves the authentication and authorization of the users of the application. When we are developing any web application, then the most important thing that we need to take care of its security. That means we need to make sure that only authenticated and authorized user can access our webpage.
The following are the aspects we are going to be dwelling into;
1.    Authentication and Authorization
2.    Types of Authentication
3.    How to implement security features in our application

What is Authentication?

Authentication is a process to ensure and confirms a user’s identity and whether the user is registered or not to access particular data or web pages. In other words, we can say that it is a process to validate someone against some data source.
A better way to understand Authentication is look at it from a layman’s point of view. Assuming we have Csharp Naija has IT Company with departments like Reception, HR Section, Accounts Section, Server Room, etc. At the gate, we have biometrics to verify every employee. If an employee arrives at the gate, biometrics checks the employee credentials against some data source and if it found the employee is a valid employee then it only allows entering into the premises. This is nothing but Authentication.

What is Authorization?

Authorization is a security mechanism which is used to determine whether the user has access to a particular resource or not. We need to understand that, authentication happens first, then only authorization. Let us have a plan example by using the Csharp naija company as in the authentication above.

From our assumption in authentication above, once the employee is authenticated then he enters into the company premises. Then Authorization comes into the picture. Within the company, in which department he may be allowed entering is determined by the Authorization process. This is basically done by the Role of the user. If the user is having list privileges then he may not allow to each and every department. On the other hand, if the user is having the highest privileges then he may be allowed entering to each and every department.

Types of Authentication


The different types of Authentication supported by ASP.NET MVC are as follows:
1.     Forms Authentication: In this type of authentication the user needs to provide his credentials through a form.
2.     Windows Authentication: Windows Authentication is used in conjunction with IIS authentication. The Authentication is performed by IIS in one of three ways such as basic, digest, or Integrated Windows Authentication. When IIS authentication is completed, then ASP.NET uses the authenticated identity to authorize access
3.     Passport Authentication: It is a centralized authentication service (paid service) provided by Microsoft which offers a single logon and core profile services for member sites.
4.     None: No Authentication provided. This is default Authentication mode.

In web.config file of our application, we can specify the Authentication mode as either Windows, Forms, Passport or None as shown below.

<authentication mode=”[None | Forms | Windows | Passport]”>
</authentication>

Web.config sample
<system.web>
    <authentication mode="Forms" />
    <!--<authorization>
      <allow roles="Admin"/>
      <deny users="*"/>
    </authorization>-->
    <compilation debug="true" targetFramework="4.7.2" />
    <httpRuntime targetFramework="4.7.2" />
  </system.web>

Different ways to implement Authentication in MVC


There are many different ways to implement Authentication in MVC.

We are going to be implementing authentication using FormsAuthentication or ASP.NET Identity.

 FormsAuthentication in ASP.NET MVC


Whenever we develop a web application, three things are common, these are Sign up, Sign in and log out. We are going to discuss how to use Forms Authentication in MVC application to achieve the above mentioned security properties of our web site.

Let us start the implementation.


Database Creation


Let us create a new database for the security implementation in our site, lets call the database CsharpnaijaSecurityDb.

Connect to our Database Server as shown below




Select Server type, Server name and authentication type and click on connect as shown above.





Right click on Databases folder to create a new database as shown above

Expand the created Database and right click on tables folder to create a new table called Employee as shown below

                                                                                                                            

Create ASP.NET MVC Application

Refer to our previous DataDriven Web Application to create a new ASP.NET MVC Web Application.



Adding ADO.NET Entity Data Model

Here we need to use the Entity Framework Database First Approach to create the Entities (Employee, Users, Roles and UserRoles) from the CsharpnaijaSecurityDb database that we created in our previous step.

We name our context class name as CsharpnaijaSecurityDbEntities. Once the EDMX file is created build the solution. In this article, we will discuss how to use the Employee and Users entities and in the next post, we are going to how to use Roles and UserRoles entities. The EDMX file should looks as shown below.


Creating Employees Controller

Save and build the application by clicking on Build on the Menu bar then select and click on Build.


Now right click on Controller Folder, select Add Controller, to select the MVC 5 Controller with Views, using Entity framework option to create the controller and click on Add as shown below.



After selecting the above controller, click on the ADD button which will open the following popup for providing the required information to create the controller with necessary actions and related views.


As you can see in the above image, you need to select the Model class as Employee and the Context class as CsharpnaijaSecurityDbEntities. Provide the controller name as EmployeesController and then click on the Add button which will create the EmployeesController.

Now the employee controller is created with the required action methods and views to perform the CRUD operation against the Employee entity. Run the application and test by yourself.


Here we are not going to focus on how it performs the CRUD operation rather we are going to focus on how to implement the Forms Authentication.

Now, the above application is accessible to each and everyone without any restrictions. Now we need to provide security to this application. So the user with proper credentials can only be able to access our application. To achieve this we are going to use the Forms Authentication.


Implementing Forms Authentication in MVC


To implement forms authentication in MVC, we can use the template provided by ASP.NET MVC developers,

The user login, Logon and Logout are all pre-created when we choose Individual Account Users radio button during creation of ASP.NET Web Application as can be seen below.

To enable the authentication, change default connection string in the web.config to point to our database as shown below


Save and run the application by click on the run icon on the menu bar, our web application will launch and display Home page as shown below



To allow entity framework create user, role and userrole tables just click on the Register button from our running

Fill in the required fields and click on Register, the web application will register you as a user there by creating all the necessary tables in our database as you can see below.

To enable authentication to our web application, just add Authorize attribute to every controller we want to authenticate as shown below

Now add an Employee Link to Layout file to provide employee menu as shown below

Run the application again and click on the Employee menu without signing in.

The system displays a Login window for you to login and continue as shown below


Now enter your credentials or register if you are not registered already. The application gives you access thereafter.

We will look at authorization in the next article.

Thank you

Comments

Post a Comment

Popular posts from this blog

Classes in C# Explained

C# Class Explained A class is nothing but an encapsulation of properties and methods that are used to represent a real-time entity, as explained by Guru99 . For instance, if you want to work with Guest’s data as in our previous DataDriven Web application . The properties of the Guest would be the Id, GuestName, Address, Phone number etc of the Guest. The methods would include the entry and modification of Guest data. All of these operations can be represented as a class in C# as shown below. using System; namespace CsharpnaijaClassTutorial {     public class Guest     {         public int Id { get ; set ; }         public string GuestName { get ; set ; }         public string Address { get ; set ; }         public string WhomToSee { get ; set ; }     ...

ASP.NET MVC Views

Views in ASP.NET MVC Application explained Find a related article By  Steve Smith  and  Luke Latham from Microsoft Corporation here In the Model-View-Controller (MVC) pattern, the  view  handles the application's data presentation and user interaction. A view is an HTML template with embedded  Razor markup . Razor markup is code that interacts with HTML markup to produce a webpage that's sent to the client. In ASP.NET MVC, views are  .cshtml  files that use the  C# programming language  in Razor markup. Usually, view files are grouped into folders named for each of the application's  controllers . The folders are stored in a  Views  folder at the root of the application as shown: The  Home  controller is represented by a  Home  folder inside the  Views  folder.  The  Home  folder contains the views for the  About ,  Contact , and  Index...

ASP.NET MVC Routing

ASP.NET MVC Routing ASP.NET MVC routing is a pattern matching system that is responsible for mapping incoming browser requests to specified MVC controller actions. When the ASP.NET MVC application launches then the application registers one or more patterns with the framework's route table to tell the routing engine what to do with any requests that matches those patterns. When the routing engine receives a request at runtime, it matches that request's URL against the URL patterns registered with it and gives the response according to a pattern match. Routing pattern is as follows A URL is requested from a browser, the URL is parsed (that is, break into controller and action), the parsed URL is compared to registered route pattern in the framework’s route table, if a route is found, its process and send response to the browser with the required response, otherwise, the HTTP 404 error is send to the browser. Route Properties ASP.NET MVC routes are res...