Quick look at security in MVC3

I learned about some security features in MVC3, that I had forgotten about.  So, let’s discuss them and the differences between authenticate and authorization as well as look at some standard attacks.  MVC3 out of the box supports Windows and Forms based authentication, Windows authentication are generally used for intranet applications and Forms based is general used for internet based applications.  With forms authenticate SSL needs to used to help protect the username and password being entered by the user.

To secure a controller action you can use the [Authorize]  attribute to secure an action or the controller itself.  If you use just the [Authorize] attribute, all you are really saying is you don’t want anonymous users to access the controller or action.  You can further define this by adding Roles or Users to the [Authorize] attribute, which is the authorization part of security in MVC3.

Now let’s talk about site attacks.

Cross-Site Scripting, which are defined as cookie theft, malware downloads, account hijacking, and modify content to name a few.  This is controlled by the underlying framework, however you can use [AllowHtml] attribute to the model property you would like to allow Html to flow through with minimal risk.

The Anti Cross Script library can be used to help sanitize the Html.

Cross site request forgery can be combated with the @Html.AntiForgeryToken() on your form declaration and ValidateAntiForgeryToken attribute on the post destination action in the controller.

In the View form definition.

[sourcecode langauge=”csharp”]
@using (Html.BeginForm("Contact", "Home")) {

In the Controller Action

[sourcecode langauge=”csharp”]
[OutputCache(NoStore=true, Duration=0)]
public ActionResult Contact(string message = null)
EmailModel email = new EmailModel();
ViewBag.Message = message;
return View(email);

Hopefully this give some insight into security options with MVC3, I will follow this up with MVC4 here soon.

Leave a Reply