How will you implement authentication and authorization in MVC 5?

Introduction

Authentication Filter is a new feature in MVC 5 this filter run before any other filter, this filter is used to authenticate User which was not there in older version [MVC 4] there we were using Authorization filter or Action filter to Authenticate User, now new updated of MVC 5 this cool feature is available.

Here in this article we are going to Create Custom Authentication Filter.

How will you implement authentication and authorization in MVC 5?

For Create Custom Authentication filter we need to inherit IAuthenticationFilter Interface.

This interface has 2 methods

  1. OnAuthentication
  2. OnAuthenticationChallenge

OnAuthentication: - In this method we are going to Authenticates the request.

OnAuthenticationChallenge: - this Method gets called when Authentication or Authorization is failed and this method is called after Execution of Action Method but before rendering of View.

How will you implement authentication and authorization in MVC 5?

After understanding what is Authentication Filter let's create a project and see demo.

Create New Asp.Net MVC Application

From Visual studio 2015 IDE Start page click on "New Project" link.

How will you implement authentication and authorization in MVC 5?

After clicking on "New Project" link a new dialog will pop up.

In that we are going to select web templates from left pane after selecting web template, we find only one project template in it "ASP.NET Web Application" just select that.

How will you implement authentication and authorization in MVC 5?

After selecting this project template next we are going to name project as "MVC5DEMO7" and clicking on the OK button a new dialog will pop up with Name "New ASP.NET Project" for selecting project Templates.

How will you implement authentication and authorization in MVC 5?

In this dialog we are going to choose MVC project template and then we are going to choose Authentication type for doing that just click on Change Authentication button, a new dialog will pop up with name "Change Authentication" here we are going to choose No Authentication click on OK Button.

It will show progress bar while it is creating project.

How will you implement authentication and authorization in MVC 5?

After creating project it will show Readme html page with use links on that page.

How will you implement authentication and authorization in MVC 5?

After creating project first thing we are going add Filter folder in Project.

For adding Folder just right click on "MVC5DEMO7" and then select Add ➜ and inside that select "New Folder" and name it as Filters.

How will you implement authentication and authorization in MVC 5?

After adding Filters folder the next thing we are going add Authentication Filter in this folder to validate User is Logged in to application or not.

Adding Authentication Filter

Let's Add Authentication Filter in for doing that just right click on Filters folder then select Add ➜ and inside that select Class a new dialog will pop up with name Add New Item with default Class template selected.

How will you implement authentication and authorization in MVC 5?

Then we are going to name class as UserAuthenticationFilter and finally click on Add Button.

How will you implement authentication and authorization in MVC 5?

Below is Code Snippet of UserAuthenticationFilter

After creating Filter next UserAuthenticationFilter will inherit a class FilterAttribute and IAuthenticationFilter.

And in this filter we are just going to check Session is IsNullOrEmpty if it is NULL or Empty then we are going to set Result to HttpUnauthorizedResult ();

And in OnAuthenticationChallenge method we are going check this result is not null or Result is HttpUnauthorizedResult.

If result is HttpUnauthorizedResult then we are going to redirect it to Error View.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Filters;

namespace MVC5DEMO7.Filters
{
    public class UserAuthenticationFilter : ActionFilterAttribute, IAuthenticationFilter
    {
        public void OnAuthentication(AuthenticationContext filterContext)
        {
            //Check Session is Empty Then set as Result is HttpUnauthorizedResult 
            if (string.IsNullOrEmpty(Convert.ToString(filterContext.HttpContext.Session["UserID"])))
            {
                filterContext.Result = new HttpUnauthorizedResult();
            }
        }

        //Runs after the OnAuthentication method  
        //------------//
        //OnAuthenticationChallenge:- if Method gets called when Authentication or Authorization is 
        //failed and this method is called after
        //Execution of Action Method but before rendering of View
        //------------//
        public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
        {
            //We are checking Result is null or Result is HttpUnauthorizedResult 
            // if yes then we are Redirect to Error View
            if (filterContext.Result == null || filterContext.Result is HttpUnauthorizedResult)
            {
                filterContext.Result = new ViewResult
                {
                    ViewName = "Error"
                };
            }
        }
    }
}

After creating UserAuthenticationFilter in next step we are going to create a simple login page.

For doing that we have to create Model for login page right.

Adding LoginModel

We have created a Model in Models Folder with Name LoginModel it has 2 properties Username and Password.

How will you implement authentication and authorization in MVC 5?

After adding LoginModel in next step we are going to add UserLogin Controller.

Adding UserLogin Controller

For adding UserLoginController just right on Controllers folder inside that select Add ➜ inside that select Controller after selecting Controller a new dialog with name "Add Scaffold" will pop up for choosing type of controller to add in that we are just going to select "MVC5Controller - Empty" and click on Add button, after that a new dialog with name "Add Controller" will pop up asking for Controller name here we are going to name controller as UserLoginController and click on Add button.

How will you implement authentication and authorization in MVC 5?

After adding UserLogin Controller in next step we are going to add 2 Action Method one which handles HttpGet Request and other which handle HttpPost Request.

In Post Request we are checking ModelState is valid or not if not then we are return model to View which show error on View.

If it is valid then we are going to check Username and Password is valid or not for this demo I have hardcoded values.

The Username to "Test" and Password to "Test" and if enter Username and Password is equal then we set Session["UserID"] and redirect to Index View of Home Controller.

See below Snapshot of UserLogin Controller

How will you implement authentication and authorization in MVC 5?

Note:-

Home controller comes by Default when you create Application.

After adding UserLoginController in next step we are going to add apply UserAuthentication Filter on HomeController.

Applying UserAuthentication Filter on Home Controller

In this part we have applied UserAuthentication Filter on Home Controller.

Now if User is logged with valid credentials into application then only will be able to access Home Controller, because we have applied UserAuthentication Filter on Home Controller.

How will you implement authentication and authorization in MVC 5?

Now let's save this application and run.

Next we are going to access Index Action Method of HomeController.

URL: http://localhost:####/home/index

How will you implement authentication and authorization in MVC 5?

Wow we do not have access to this page it is redirecting to Error View because we have applied UserAuthentication Filter on it.

Next we are going to access Login Action Method of UserLoginController.

URL: http://localhost:####/UserLogin/login

How will you implement authentication and authorization in MVC 5?

After entering Valid Credentials click on Log in button to Log into Application.

Debugging of UserAuthentication filter

Below is debug mode of UserAuthentication Filter where you can see real time values and how Authentication filter works.

How will you implement authentication and authorization in MVC 5?

How will you implement authentication and authorization in MVC 5?

How will you implement authentication and authorization in MVC 5?

After entering Valid Credentials we have passed Authentication check and we have been redirected to HomeController as show below.

How will you implement authentication and authorization in MVC 5?

If we enter Invalid Credentials then we cannot Login and if we cannot login then we cannot access Home controller.

How will you implement authentication and authorization in MVC 5?

Final we have completed understanding Authentication Filter a New feature in MVC 5 I hope you have enjoyed in this reading this article.

How is form authentication implemented in MVC?

The following three steps are required to implement Forms Authentication in an MVC application..
In the web. config file, set the authentication mode to Forms..
FormsAuthentication. SetAuthCookie is required to use for login..
Again FormAuthentication. SignOut is required to use for logout..

How to create authentication and authorization in ASP.NET MVC?

Custom Authentication and Authorization in ASP.NET MVC.
ASP.NET Forms Authentication. ... .
Custom Authorization. ... .
Designing Data Model. ... .
Defining Database Context with Code First Mapping between User and Role. ... .
Code First Database Migrations. ... .
Solution Structure..
Designing the View Model. ... .
Forms Authentication Initialization..

What is authentication and Authorisation in MVC?

ASP.NET MVC Authentication is a feature in MVC that helps in making the website highly secure and safe. Authentication is the process of confirming or validating the user's identity if the user who is trying to access the web page or web application is a genuine user or not.

How did you implement authentication and authorization filter?

Let's Add Authentication Filter in for doing that just right click on Filters folder then select Add ➜ and inside that select Class a new dialog will pop up with name Add New Item with default Class template selected. Then we are going to name class as UserAuthenticationFilter and finally click on Add Button.