Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Security to Actions in MVC Application

0.00/5 (No votes)
22 Oct 2013 1  
This article explains how to provide security to action in MVC applications

Introduction

In this tip, I will try to explain about achieving security to MVC application. Normally in Web forms, the security to the particular page can be established using sitemap control or putting some code in a page_load event of either Site master or a particular page you needed. In this tip, what I am going to do is the same way as the web forms in MVC Apps.

Background

In my application, I would like to include Role Management, Role in this sense is a list of users having some common feature, for example, say Student, Librarian, Teacher, etc. so that when a particular user is logged into the system, she/he should get the corresponding Views/Pages. When Student Role User gets Logged into the system, he should get the particular Views of student only.

Will Start?

Let us create an MVC application. I will choose this as an internet project, I will name the project as SecurityInMvc. We can notice that Accountcontrol and Account Model got created by itself when we created a new project, which provides us authentication of type FormsAuthentication. I don't go further on FormsAuthentication. If you run this project, you can see that:

In the above View, you can see that there is a Register link at Right Corner, just Register one client and try to login, here there will be no problem because it is inbuilt by framework.

Problem

Here, I created myself an account which is stored in the database. Now at present, I am able to access both About and contact View, Now my requirement is that I should not be able to use About View for security purposes. How can I do this? I may do like this Remove About link for this role. Will this solve our problem? Definitely No. Because they can access the page through URL. Here is the place we needed to restrict the access.

Solution

Now I will make About View not accessible to this user through any other ways.

[RoleAuthorize(Roles="Admin")]
public ActionResult About()
{
    ViewBag.Message = "Your app description page.";
    return View();
} 

Here to the above Action, I have given some restrictions that only admin Role users can access this action.

But here, how should the Action know the logged in user belongs to which role. To figure that out, we need to do one more little thing.

You might have noticed the App_Start folder when you created an MVC application.

In the App_Start folder, there is file called FilterConfig.cs which will execute when action call happens, we can do whatever we need. So it will create a custom file that restricts unauthorized user access.

Right click on Filter folder, click Add New Item, then choose a class file name - it can be anything you want, I will name it as RoleAuthorize.cs.

using System.Web.Mvc;
namespace MvcApplication5.Filters
{
    public class RoleAuthorize : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (!httpContext.Request.IsAuthenticated)
                return false;
            userloginDb obj = new userloginDb();
            string role=obj.GetRoles(1);
            foreach(string DefinedRoles in this.Roles.Split(','))
            {
                if (DefinedRoles.Equals(role))
                    return true;
            }
            return false;
           
        }
    }
} 

In System.Web.MVC, there is a class called AuthorizeAttribute which has some virtual methods in that we need to override AuthorizeCore method which accepts input as HttpContextBase which includes some information about login details such as login user name and Authentication type, etc. and returns bool.

How This Works?

When a request happens to About action automatically before executing About Action, the control moves to Filter which we have defined, i.e., RoleAuthorize.cs.

Here at very first, it will check whether the user is Authenticated or not. If not, it returns false and About Action doesn't get executed and it moves to login page. If it is authenticated, then I have defined a method called GetRoles() which accepts input as username which is there in the HttpContextBase object.

this.Roles() will get you the roles which are mentioned above each action and now what we need to do is just compare between these two stings, if they match, return true.

Conclusion

We can achieve security to each action using Filters.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here