Click here to Skip to main content
15,891,513 members
Articles / Programming Languages / C# 4.0
Tip/Trick

Security to Actions in MVC Application

Rate me:
Please Sign up or sign in to vote.
4.83/5 (3 votes)
22 Oct 2013CPOL3 min read 18.9K   257   9   8
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:

Image 1

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.

Image 2

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.

C#
[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.

Image 3

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.

Image 4
C#
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer TWB BANGALORE
India India
I Started my Programming career with C#.Currently using C#, ASP.NET, WCF, AJAX, & ASP.NET MVC to create Information Systems.

My interests involves Programming, C# is the best programming language and I love working with C# and other Microsoft Technologies.

Comments and Discussions

 
QuestionGud one....shivaraj Pin
shivaramakrishnaReddy23-Oct-13 22:35
shivaramakrishnaReddy23-Oct-13 22:35 
AnswerRe: Gud one....shivaraj Pin
Shivarajbk24-Oct-13 1:14
Shivarajbk24-Oct-13 1:14 
Generalauthorization in MVC Pin
Member 1035523723-Oct-13 5:41
Member 1035523723-Oct-13 5:41 
GeneralRe: authorization in MVC Pin
Shivarajbk23-Oct-13 21:25
Shivarajbk23-Oct-13 21:25 
Generalthanks Pin
qholamhoseyni22-Oct-13 6:41
qholamhoseyni22-Oct-13 6:41 
very good.
thanks
GeneralRe: thanks Pin
Shivarajbk23-Oct-13 0:55
Shivarajbk23-Oct-13 0:55 
QuestionNo images Pin
Ravi Bhavnani22-Oct-13 4:23
professionalRavi Bhavnani22-Oct-13 4:23 
AnswerRe: No images Pin
Shivarajbk23-Oct-13 0:55
Shivarajbk23-Oct-13 0:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.