Authorization Filter in ASP.NET MVC

Authorization Filter in ASP.NET MVC

What is MVC Authorization Filter?

ASP.NET MVC Filter is a custom class where you can write custom logic to perform before or after the execution of an action method. Filters can be applied to an action method or controller declaratively or programmatically. Declaratory means of applying a filter attribute to an action method or control class and programmatic means by implementing a corresponding interface.

Why should we use authorization filter in MVC?

By default, in the ASP.NET MVC application, all modes of action of all controllers are accessible by authenticated and anonymous users. But if you want the action methods to be available only to authenticated and allowed users, then you have to use the authorization filter in MVC.

The authorization filter provides two built-in attributes like Authorize and Allow Anonymous that we may use according to our business requirements. Understand the “Enable” and “AllowAnonyme” filters using an example.

Understanding permission filters in the ASP.NET MVC application:

To understand permission filters, let’s create a new ASP.NET MVC application. Open Visual Studio in Admin mode, then Choose File => New Project.

When you click on the Project link, the New Project dialog window is displayed.  In the New Project window, select the Web tab located under the Visual C# tab which is again located in the Installed – Templates section. From the center panel, select the ASP.NET web application, name the project “AuthorizeinMVC” and click the OK button.

 Again, in the Add Folder and Base Reference section, select the MVC Checkbox checkbox because we will create an MVC application.  Once you click the OK button, a new dialogue window opens with the name New ASP.NET project to select project templates. Again, in the Add Folder and Base Reference section, check the MVC Checkbox box as we will create an MVC application.

We need to change the type of authentication by clicking on the Change Authentication button. A new dialogue box will appear with the name Change Authentication here, we will choose No Authentication and then click on the OK button.

Creation of the Home controller

Right-click the ‘Controllers’ folder and add a controller with the HomeController name. Once you have created the Home Control, copy and paste the following code.

public class HomeController: Controller
{
    public ActionResult NonSecureMethod()
    {
        return View();
    }

    public ActionResult SecureMethod()
    {
        return View();
    }
}

In the above, you can observe that we have created HomeController with two action methods i.e. NonSecure Method and SecureMethod. We want the secure method to be accessible by authenticated users whereas the insecure method is accessible by anyone.

Creation of a connection controller

Right-click the ‘Controllers’ folder again and add a controller named LoginController. Once you have created the connecting controller, copy and paste the following code.

public class LoginController: Controller
{
    public ActionResult Login()
    {
        return View();
    }
}

As you can see, we create the above connection controller with a method of action, that is to say, log in. Each time an authenticated user wants to access the secure method, we need to redirect that user to the Login action method.

Creating a NotSecureMethod view.

Right-click NonSecureMethod() and add a view with the name NonSecureMethod. After you have created the view, copy-paste the following code.

@{
    ViewBag.Title = "NonSecureMethod";
}

This method is a non-secure method

Set up SecureMethod View.

By the same token, right-click SecureMethod() and add a view with the SecureMethod name. Then copy and paste the following code into the SecureMethod.cshtmlview.

@{
    ViewBag.Title = "SecureMethod";
}
This method as it SecureMethod

This method as it SecureMethod

Creating Login View

Also, right-click on Login Controller’s Login() method and add the view with the name Login. cshtml. Copy and glue the following code into Login.cshtml view.

@{
    ViewBag.Title = "Login";
}
Login Page

Login Page

At this stage, authenticated and anonymous users can access both the SecureMethod method and the NonSecureMethod method using the following Two URLs.

Home/SecureMethod

Home/NonSecureMethod

If you want the “SecureMethod” to be accessible only by authenticated and authorized users, you must decorate this method with the “Authorize” attribute as shown below.

[Authorize]
public ActionResult SecureMethod()
{
    return View();
}

Changing the web. config file

Made the following changes to the web. config file. What we do here is that if the user is an unlicensed user, then we simply navigate that user to the login page. So, add the following code under the system. web section of the web. config file.

<authentication mode="Forms">
      <forms loginUrl="/Home/Login"></forms>
</authentication>

That’s it. Now start the app and browse to/Home/SecureMethod. After that, you will see that it will redirect you to the Login page. Instead, the NonSecure method can be accessed.  Now remove the Authorize attribute from HomeController Method Security.    Then apply the Allow attribute to the controller as shown below.

[Authorize]
public class HomeController : Controller
{
    public ActionResult NonSecureMethod()
    {
        return View();
    }
    public ActionResult SecureMethod()
    {
        return View();
    }
}

When you apply the Authorize attribute to the controller, then it applies to all of the action methods present in this controller.    Here, all Home Controller action methods are now protected with the Authorize attribute, so only authenticated users can access both SecureMethod() and NonSecureMethod() at the same time.

How do I set the AllowAnonymous attribute in MVC?

If you want to allow anonymized access to the NonSecureMethod of the Home controller, then you have to decorate the AllowAnonymous attribute of this NonSecureMethod method as shown below. The AllowAnonymous attribute in MVC is used to override the authorization which is applied by the authorization filter in MVC.

[Authorize]
public class HomeController : Controller
{
    [AllowAnonymous]
    public ActionResult NonSecureMethod()
    {
        return View();
    }
    public ActionResult SecureMethod()
    {
        return View();
    }
}

Now, run the application and navigate to /Home/NonSecureMethod and you will see that it displays the page as scheduled and when you access /Home/SecureMethod, it redirects you to the Login page. 

Conclusion

In ASP.NET MVC, a user request goes to the appropriate controller and action method. However, there may be circumstances in which you want to run logic before or after the execution of an action method. ASP.NET MVC provides filters to that effect. In this blog, we have learned Authorization filters in Asp.Net MVC.

iFour Technolab Pvt. Ltd. of a reputed Office 365 Addin Development Company with years of experience in building large scale enterprise web, cloud and mobile applications using latest technologies like ASP.NET, CORE, .NET MVC, Angular and Blockchain. Keen interest in addressing business problems using latest technologies and help organization to achieve goals.



            

Leave a Reply

Your email address will not be published.