How can prevent Cross-Site Request Forgery in MVC? Part 1

What is Cross-site request?

wikipedia: is a type of malicious exploit of a website whereby unauthorized commands are transmitted from a user that the website trusts. more info click here

You have a Logout function in AccountController that users use it to exit from the site. Now assume you have a forum in your site and user should login to your forum to post comments or read them, one of the ability in your forum is that users can upload an image now a devil user upload an image in this way with malicious content:

<img src="/account/logout" />

From now on, each user that visit this page, automatically sign-out from the site, because the Logout function is run automatically by the page.

Token Verification:

You can use token verification to prevent this attach, first you should use @Html.AntiForgeryToken() inside the Form Tag that you want to submit or you want to post to the controller :

<form action="/account/logout" method="post">
@Html.AntiForgeryToken()
…
</form>

Then you should put [ValidateAntiforgeryToken] above the function that is called by the submit button from the view file.

[ValidateAntiforgeryToken]
public ActionResult logout
{
//put your code here
}

How it works?
@Html.AntiForgeryToken() generates a code like this:

<input type="hidden" value="012837udny31w90hjhf7u">

The value of the Token will be compared before running the function that uses [ValidateAntiforgeryToken], if both values will be same the function will be fire, by this method if the function is called from other places or by malicious code it won’t be run.

Advertisement

2 thoughts on “How can prevent Cross-Site Request Forgery in MVC? Part 1”

  1. You could also as a complement require POST whenever you are making updates or accepting commands. That way image links cannot cause trouble.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s