Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to prevent parameter tampering and send values with Javascript?

I am posting a form to the controller and making it asynchronous. I am storing values in input form hidden. When a button is clicked, a javascript function is called. It both fetches the value from an input field, as well as a value from input form hidden. It then sends a json string to the controller to handle this request.

Controller:

[HttpPost, Authorize] 
public ActionResult DoSomeStuff (string leagueName, string doSomething)  {
    var service = new Service(_db);
    var league = service.GetLeague(leagueName);
    if (league != null) {
        // validate doSomething
        league.Action = doSomething;
        _db.SaveChanges();
    }

    return new EmptyResult(); 
}

Javascript:

$(document).on("click", "#submitForm", function () {
    var json = {
            "leagueName": $("input[name=leagueName]").val(),
            "doSomething": $("input[name=doSomething]").val()
    };

    $.post("/Home/DoSomeStuff/", json, function () {
        // async display something
    });
}

Html:

<input type="text" name="doSomething">
<button type="submit" id="submitForm"</button>
<input type="hidden" name="leagueName" value="@item.League.LeagueName" />

What is the best way to let javascript fetch a stored value (more secure way then input type hidden)?

How can I prevent some user from altering the value from the input type hidden field?

like image 463
Darri Steinn Konn Konráðsson Avatar asked Mar 15 '23 01:03

Darri Steinn Konn Konráðsson


1 Answers

How can I prevent some user from altering the value from the input type hidden field?

You cannot!

What is the best way to let javascript fetch a stored value (more secure way then input type hidden)?

The general rule is, do not trust data coming from client. You should always validate it on server before doing anything.

If you are worried about a user update the league name field value in the form to some other users league name and post it, What you should be doing is, explicitly checking whether the user has proper permission to do something on the posted league in your server code.

[HttpPost, Authorize] 
public ActionResult DoSomeStuff (string leagueName, string doSomething)  {
    var service = new Service(_db);
    var league = service.GetLeague(leagueName);

    // Now check whether the current user has access/permission 
    // to perform some operation on this league.
    // Ex : if(!service.IsUserAuthorizedToDoSomething(league))
    //     {
    //      return View("NotAuthorized");
    //     }
    //to do: Return something
}
like image 136
Shyju Avatar answered Apr 06 '23 21:04

Shyju