BelgianR
BelgianR

Reputation: 45

How to secure ajax call (JS to PHP)

my question is simple, but I can't find any updated informations about it.

Basically, I've a phonegap application :

And php files on OVH server.

When the application need to CRUD the database (mysql-ovh), it's been done with ajax call.

For example :

if(confirm("Delete record ?")){
    params = { 
        "action": "delete_record",
        "record_id": record_id
    }
    ajax_post(params, function(data){
        if(data.status == 'success') {
            alert(data.msg);
            $.mobile.changePage( "aRandomPage.html");
        } else {
            alert("erreur : " + data.msg);
        }
    });
}

NB : ajax_post is just a personalized function doing a simple ajax post so I don't have to write all informations such as file URL and so on.

The problem is that ANYONE could edit the javascript file (Either by unzipping the .apk, .xap or by console if it is a web version) and transform the params to

params = { 
    "action": "delete_record",
    "record_id": 5
}

and delete the record number 5 (which is not his and he shouldn't be able to) or whatever record he wants, and doing so, he could delete all records.

Is there a classic way to handle this I'm not aware of ?

I came up with a solution : I could store the password in the storage.setItem(""), and everytime there is an access to the database through ajax, I would pass the userid (already stored in storage) and the password. Then I would check on PHP side if password and ID are matching (Kind of a loggin thing).

That way, I would be sure the user sending the request is the owner of the record and can delete it. (I don't see how someone could bypass that since it would require the password of the user)

Downside is to store password on client, not sure it's any better..

Thanks in advance,

Upvotes: 1

Views: 639

Answers (1)

Barmar
Barmar

Reputation: 782226

You need to require the user to login first. When they login, a session variable can be set in PHP with the user ID. Then when the delete_record request is made, you check whether the user ID has permission to delete that record.

Upvotes: 1

Related Questions