Click here to Skip to main content
13,835,559 members
Click here to Skip to main content
Add your own
alternative version

Tagged as


100 bookmarked
Posted 17 Sep 2013
Licenced CPOL

Security In ASP.NET MVC

, 21 Sep 2013
Rate this:
Please Sign up or sign in to vote.


In this article i would like to explain some security measures that you should be aware  of while developing an secure ASP.NET MVC application. Here i am explaining about

  • Authentication
  • Authorization
  • XSS
  • CSRF(Cross Site Request Forgery)   


  When you authenticate a user, you are verifying the identity of a user. If you need to verify a user in an MVC application it is  probably because you are building an application that restricts access to specific users. This is completely separate from authorization, which is determining whether a specific person is allowed to do certain action.<o:p /> 

There are two authentication mechanisms in MVC : 

 Forms Authentication<o:p />  

        Form based authentication is providing an input form where users can enter the username and password with accompanying logic in the application needed to validate those credential. MVC provides a lot of infrastructure support for Forms Authentication. Forms authentication is highly customizable , you can customize everything from the sign in form,  to where the credentials are stored and how those credentials are validated. Forms Authentication in ASP.NET relies on cookies by default. Once the user is signed in to an Application the runtime can issue a cookie on the browser. The browser will then send the cookie  with every subsequent request to the application.  ASP.NET will see the cookie and know that the user is already authenticate and does not need to sign on again.<o:p /> 

   Note: word of warning , SSL is required to make Forms authentications secured. If you are running the application over http anybody snooping the network can see the users credentials. 

Windows Authentication<o:p />  

 Windows Authentication is also known as integrated authentication because user components that built in to the Windows operating system are used to authenticate users . Once a user is logged in to a domain, windows can automatically authenticate them in to application. Windows Authentication is commonly used in Intranet Apps that run inside a company's firewall  where all of the users are logged in-to a windows domain. It will provide a single sign on experience.They sign on once in a domain and can be authenticate to several intranet apps.<o:p /> 

When we choose a Forms Authentication and Windows Authentication?<o:p>  

  •  If you want to build a public websites then  Forms Authentication is best because  it can be used outside of a windows domain. 
  •  If you want to build an Intranet application which runs with windows identity use Windows Authentication.<o:p> 

How is Forms Authentication configure?<o:p /> 

First we need to change the configuration in web.config like below<o:p>  

This bit of configuration tells runtime when we need to authenticate the user redirect the browser /Account/Logon. This Account controller and this Logon view as well as some other view allow me to register on site. These things are provided by default in ASP.NET MVC internet template. Everything needed for the Forms Authentications are along with this template. 

Selecting the Forms Authentication template

<o:p>Open Visual Studio 2010 >> New Project >> Select ASP.NET MVC4 Web Application and Click Ok 

 And then select Internet Application Template which gives us to everything needed for the Forms Authentication like AccountController, Views etc and then click OK. 

<o:p />


The Authorize attribute doesn’t really care about how we authenticate a user. We can use a Form Authentication or Windows Authentication. All authorize cares about that the user does have an identity and we know whom they are and it’s  not  going to let  a anonymous user get in to the Index action. When we going to take an index action without authenticating it automatically redirect to Account/Logon because the user has no account in this application. So we need to register for to Logon.  

How we are Authenticate with Windows Authentication?<o:p />

                First we need to change a little bit in the configuration section like below in the web.config file.<o:p> 

Then apply the authorize attribute to the index action 

You can apply authorize filter to an individual action method or to a controller. When you apply a filter to a controller, it works as though you had applied it to every action method in the controller class applied the Authorize filter to the class, so all of the action methods in the Account controller are available only to authenticated users.<o:p />

                In order for windows integrated authentication works   we need to enable windows authentication in IIS Express else we got the below error and this is the scenario you commonly face in today’s server configuration. 

Server programs’ like Web services and Database services typically have features turn off by default to reduce the attack surface. If we want to become Windows Authentication works we need to turn it on.<o:p />

Go to Document >> IISExpress >> config >> applicationhost.config file and windows authentication enable to true.<o:p> 

You can take authentication details like below  

Authorization<o:p />

                The authorize attribute also allows you to set some parameters to enforce authorization rules. First we need to know the user’s identity and then we can say only the specific identities to allow accessing these actions.<o:p /> 

Authorize attribute also allows you to specify the Roles. In Windows Authentication by default map to Windows groups on server or groups configured in the active directory. You can put roles like below 

In Forms Authentication ASP.NET has a role provider. By using these you can store, manage roles in a SqlServer database. These can configured in the application by default.The easiest way to do that is use the below button in the solution explorer 

It launches ASP.NET configuration tool .This is the tool you are only going use in the local development machine. It’s going to look in the web.config location and use the same application services database as that Form Authentication provider of using that is already configured inside of there. You can add , manage roles from here. While doing these it automatically map to db we are configured in the web.config file. 


                There are some specific threats we will face. One popular attack of this phase is Cross Site scripting attack or XSS. In Cross scripting attack the malicious user will try to have your website load a malicious script in to the user’s browser. It could be a malicious script, active-x control and even some malicious html. The malicious scripts can theft the cookie, Modify user settings, Download Malware, Modify content. One of the worst cross site script attack is Account Hijacking; the malicious users can access the user’s credentials and personal information.  

Once this happen, your users become vulnerable to any number of problems. 


                This is a simple application for saving employee information. Let I am putting some html tag like I am from <em>India</em> and then I try to save this , ASP.NET automatically reject this request to prevent Cross site scripting attack because the ASP.NET is going to look for anything that resembles the html and just reject the request. Actually there is no wrong with the emphasis tag but ASP.NET is not trying to make a distinction here anything that looks like html is going to be rejected. 

Sometimes user need to upload some html in to the server then there are always circumvents this request validation. You have to extremely careful. One option is put ValidationInput attribute to the destiny here in Create action.  

So you can successfully process this request<o:p> 


                Now we can have a problem that html encoded here this is because razor is going to encode everything by default which is good. There is another defense against the cross site scripting and we can fix that easily however the validate input false is completely disabling the check for cross site scripting malicious html and really we only need html inside of one specific property. So you can allow html to one property using AllowHtml attribute. Also some changes need to be done, remove ValidateInput attribute from the Create action and also make sure that we should pass EmployeeViewModel class as action parameter that means model binding will takes place will move the html in to that property. Also one change in the view to show the html without encoding by putting ViewData in Html.Raw helper.<o:p /> 

And then again going to save one more and display the ViewData in the same view contain html tag.<o:p> 

Anti XSS Library 

                Someone come to a form and enter some script like below<o:p> 

It’s also more malicious. Fortunately Microsoft provide a library for prevent this. You can download it via nugget or Library Package Manager Console (Visual Studio>>Tools>>Library Package Manager>>Package Manager Console and type Install-Package AntiXSS and press enter).

<o:p />

                What I am going to do I am putting a line of code in the below Edit action post method<o:p /> 

And this code will remove all the malicious things.<o:p> 

 Cross Site Request Forgery 

                Cross Site Request Forgery is a dangerous and extremely major attack. Imagine a user come in to site and trying to update some information that requires authentication before they are allowed to perform update. Once the user logs in the Form Authentication your site will be sent the users browser an authentication cookie and every subsequent request of the site the users browser will send that cookie along and ASP.NET will see the user is already be authenticated. There is nothing wrong with the browser to sending the cookie along this is how the browser and cookie works that means the user doesn’t need to enter the username and password in every single request they make. They authenticate themselves once and the cookie will allow them to remain authenticated at least for the duration of the session <o:p />

Then what is the problem?<o:p />

                If the user visit some other site or strict in picking up some html from a malicious source  which had bad intention , then this malicious source can and provide a form just like a form that our application would given to the user and then if the user submit the form the call again will be authenticated because the authentication  cookie be gave to the users browser always travel along every request and will save the information in to the database like we always do one we have authenticated  request. Only the information in the request probably is in something user wants to submit. Someone strict the user in to transferring money or editing their account. The problem here is that not simply say we need the user to be authenticated when submit some information. We also have to be checking the information that the user is submitting coming from a form that our application presented to the user. We want to be preventing them when submitting the form from a malicious source.<o:p /> 

Demo<o:p />

                To demonstrate a CSRF I am applying the authorize attribute to my two Edit action methods of my application.<o:p> 

I can save, edit the records because I had already authenticated. Below is a sample record that I had saved in to the database successfully<o:p /> 

In the developer point of view we are confident that I having authorized attribute in place for preventing malicious user from edit an Employee details. <o:p />

                Watch would happen that I logged in as a user. Come across an interesting link   in my system


May be this link will you get from an email or from another website or some other areas of internet. Now I am going to click the link and seen a page will up.  

Now look at the record that we had saved earlier has changed. What happen? 

<o:p /> 

Look at the source code of the link  

Look at the action that form point to which has the same URL where the employee is posted. The form contains all of the input needed for to complete the request and also at the bottom some line of JavaScript for automatically submitting the form when the page loads.<o:p> 

How can we prevent this?<o:p />

Use @Html.AntiForgeryToken() inside the form tag. This token will add a hidden input value that is unique to browsing session. Also sending a matching value in a cookie to the users browser so the user has accepts this cookie and that something malicious website would not be able to do. <o:p />

                Also you should put an attribute ValidateAntiForgeryToken for matching the form value and cookie value<o:p /> 

I again going to edit my record what the malicious user had done. Now I am going to click that link again and the ASP.NET MVC thrown an exception that AntiForgeryToken is not supplied or invalid.<o:p> 

Hope you are enjoyed my article very well...Expecting your valuable suggestions…enjoy programming…<o:p /> 

<o:p />


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Jameel VM
Software Developer (Senior) Orion India Systems
United States United States
Software Engineer At Orion System Integrators,New Jersey,United States Of America and have an experience of more than 4 years in Microsoft Technologies.

Article of the Day on Microsoft's site on Friday, September 20, 2013.
My Blog :

You may also be interested in...

Comments and Discussions

GeneralMy vote of 2 Pin
DarshilPandya7-Sep-17 23:02
memberDarshilPandya7-Sep-17 23:02 
QuestionCSRF token changes not working on live Pin
alok lingayat12-Dec-16 18:46
memberalok lingayat12-Dec-16 18:46 
GeneralMy vote of 5 Pin
Rakesh Kohale13-Apr-16 21:57
professionalRakesh Kohale13-Apr-16 21:57 
GeneralMy Vote of 5 Pin
aarif moh shaikh19-Feb-16 1:53
professionalaarif moh shaikh19-Feb-16 1:53 
GeneralPerfect Article Pin
Amin Mehdikhani2-Dec-14 23:46
memberAmin Mehdikhani2-Dec-14 23:46 
GeneralRe: Perfect Article Pin
Jameel VM3-Dec-14 1:21
memberJameel VM3-Dec-14 1:21 
GeneralMy vote of 5 Pin
Elvin Yusifli9-Sep-14 3:39
memberElvin Yusifli9-Sep-14 3:39 
GeneralRe: My vote of 5 Pin
Jameel VM9-Sep-14 21:08
memberJameel VM9-Sep-14 21:08 
QuestionMy Vote of 5 Pin
Sampath Lokuge5-Jan-14 3:39
memberSampath Lokuge5-Jan-14 3:39 
AnswerRe: My Vote of 5 Pin
Jameel VM5-Jan-14 7:32
memberJameel VM5-Jan-14 7:32 
GeneralMy vote of 5 Pin
Philip Cotan16-Oct-13 11:26
memberPhilip Cotan16-Oct-13 11:26 
GeneralRe: My vote of 5 Pin
Jameel VM16-Oct-13 20:58
memberJameel VM16-Oct-13 20:58 
GeneralMy vote of 3 Pin
JasonMacD14-Oct-13 11:25
memberJasonMacD14-Oct-13 11:25 
GeneralMy vote of 5 Pin
Renju Vinod6-Oct-13 21:09
professionalRenju Vinod6-Oct-13 21:09 
GeneralGreat article brother.... Pin
vimalkumar_ck24-Sep-13 10:36
membervimalkumar_ck24-Sep-13 10:36 
GeneralRe: Great article brother.... Pin
Jameel VM24-Sep-13 10:37
memberJameel VM24-Sep-13 10:37 
GeneralMy vote of 4 Pin
Michael Breeden24-Sep-13 2:54
memberMichael Breeden24-Sep-13 2:54 
GeneralRe: My vote of 4 Pin
Jameel VM24-Sep-13 4:12
memberJameel VM24-Sep-13 4:12 
QuestionThank you Pin
Pooria Lajevardy21-Sep-13 21:07
memberPooria Lajevardy21-Sep-13 21:07 
AnswerRe: Thank you Pin
Jameel VM21-Sep-13 22:04
memberJameel VM21-Sep-13 22:04 
QuestionMy vote of 4 Pin
Tony van Roon-Werten19-Sep-13 20:28
memberTony van Roon-Werten19-Sep-13 20:28 
AnswerRe: My vote of 4 Pin
Jameel VM20-Sep-13 1:09
memberJameel VM20-Sep-13 1:09 
AnswerRe: My vote of 4 Pin
Jameel VM21-Sep-13 4:02
memberJameel VM21-Sep-13 4:02 
GeneralMy vote of 1 Pin
cmputr19-Sep-13 10:46
membercmputr19-Sep-13 10:46 
GeneralRe: My vote of 1 Pin
Jameel VM20-Sep-13 1:13
memberJameel VM20-Sep-13 1:13 

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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web05 | 2.8.190114.1 | Last Updated 21 Sep 2013
Article Copyright 2013 by Jameel VM
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid