Ajax - Protect Webservices

Asked

Viewed 123 times

2

I am building an Asp.net MVC application and make many calls to actions and webservices via ajax (jquery or Angularjs). How could I hide these calls, or ensure they are made only by my app?

For example:

    $('#btnNext').click(function () {    
        $.ajax({
            url: "/Home/Next",
            type: "POST",
            data: JSON.stringify({ 'Options': someData}),
            dataType: "json",
            traditional: true,
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                if (data.status == "Success") {
                    alert("Done");
                } else {
                    alert("Error occurs on the Database level!");
                }
            },
            error: function () {
                alert("An error has occured!!!");
            }
        });
    });

That way my code is very exposed. Anyone accessing the source will be able to call my actions and webservices without my permission and get my business data as well as load the server making numerous requests.

  • In Homecontroller you have no way of knowing if the user is logged in? If so, Actionresult Next returns, otherwise no.

  • I have no way of knowing if the user is logged in because it would be in an open area of the system

1 answer

2

Implementing the following attribute:

public class PermitirCrossSiteJsonAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
        base.OnActionExecuting(filterContext);
    }
}

Note that this allows the origin of the request to be any one, because I used "*".

To allow only for your website, exchange "*" by the address of your website.

Decorate the Action:

[PermitirCrossSiteJson]
public ActionResult Next()
{
    return Json("Sou um JSON protegido", JsonRequestBehavior.AllowGet);
}

You can use the Controller also:

[PermitirCrossSiteJson]
public class HomeController : Controller
{ ... }

Support for IE9 or less?

Install this Nuget package.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.