2

I'm working on asp.net mvc application. I've few actions that returns json. These actions are called using Jquery ajax call.

This website has doesn't require authentication. Any anonymous users can access the website. I'm worried about people just calling the actions and perform DOS attack.

Is there any way we can stop people accessing the action directly?

Thank you.

Nil Pun
  • 17,035
  • 39
  • 172
  • 294
  • you can just deny `HttpGet` for JSON Action methods and allow only `Post`. Also try some thing like AntiForgeryToken in MVC. – Saravanan May 27 '13 at 12:56
  • 1
    If these requests are used in your web application and displayed publicly, then there is no difference in calling these services directly or via your web app. – emre nevayeshirazi May 27 '13 at 13:21
  • I don't have much knowledge of `AntiForgery`. But found many link to achieve this. I hope below link will help you. [Reference](http://dotnetslackers.com/articles/aspnet/Protect-ASP-NET-MVC-3-Applications-Using-AntiForgery-Helpers.aspx) [Stackoverflow link](http://stackoverflow.com/questions/1402770/what-is-the-use-of-anti-forgery-token-salt) – Amit May 27 '13 at 13:46
  • Thank you all for your comments – Nil Pun May 28 '13 at 09:19

1 Answers1

4

I thinks you can use AntiForgeryToken,

In your view you need the token so that it is available to JavaScript.Add following line the above javascript just use the common HTML-Helper.

@Html.AntiForgeryToken()

Append it to your ajax request so that you don't have to repeat yourself

$(document).ready(function () {
    var securityToken = $('[name=__RequestVerificationToken]').val();
    $('body').bind('ajaxSend', function (elm, xhr, s) {
        if (s.type == 'POST' && typeof securityToken != 'undefined') {
            if (s.data.length > 0) {
                s.data += "&__RequestVerificationToken=" + encodeURIComponent(securityToken);
            }
            else {
                s.data = "__RequestVerificationToken=" + encodeURIComponent(securityToken);
            }
        }
    });
});

And in you controller simply add standard ASP.Net MVC Anti-CSRF mechanism. like

[HttpPost]
[Authorize]
[ValidateAntiForgeryToken]
public JsonResult YourMethod(string param)
{
    // do whatever
    return Json(true);
}
Satpal
  • 132,252
  • 13
  • 159
  • 168