Ajax - Protect WebServices

2

I'm building an ASP.NET MVC application and I make lots of calls to actions and webservices via ajax (jquery or angularjs). How could I hide these calls, or make sure they are only made by my application?

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 who accesses the source can call my actions and webservices without my permission and get data from my business besides loading the server making numerous requests.

    
asked by anonymous 22.01.2016 / 13:59

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);
    }
}

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

To allow only for your site, change "*" by the address of your site.

Decorate Action :

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

You can also use Controller :

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

Support for IE9 or lower?

Install this NuGet package .

    
22.01.2016 / 15:14