dave
dave

Reputation: 15459

How to validate if it's an authorised user sending a request?

I'm stuck in this situation where I need to validate if it's the right user sending the request/information to the server. For example, a user submits a delete friend request, in the URL as parameters I include the friend's id (another member id); should I also include the member asking for the friend delete request's id?

I'm just trying to validate or make sure it's the right user sending the request. What's the best way to go about this in general? If the user is logged in can we just validate by logged in member's id? Or is there a better way?

Upvotes: 0

Views: 163

Answers (3)

andrewsi
andrewsi

Reputation: 10732

Without knowing how your authentication works, it's a little difficult to say.

When I've had to do this in the past, I've used a combination of server-side authentication to identify the user sending the request, and URL parameters to specify what they want to delete. A user needs to be logged in to send a Delete request, and I'm tracking their userID with a $_SESSION variable. So when I get a Delete request, the SQL looks vaguely like:

DELETE FROM 
    friends 
WHERE 
    userID=$_SESSION["id"] AND friendID=$_POST["friend"]

As halfer explains in the comments, this is a generally bad way of doing things, as it opens an SQL injection vulnerability in the code. You can consider a couple of ways of avoiding that.

Firstly, you can sanitize the data - if you know that your friendID is always going to be an integer, you can check for that. A regular expression to check for non-numeric characters will work - if there's anything dodgy in there, you can deal with it appropriately and not pass it to the database.

The second approach is the one I prefer - when you make your query, you can use a prepared statement, and bind the parameters to it. Using PDO, you'll end up with something that looks like:

$sth = $dbh->prepare('DELETE FROM friends WHERE userID=? AND friendID=?');
$sth->bindParam(1, $_SESSION["id"]);
$sth->bindParam(2, $_POST["friend"]);
$sth->execute();

Upvotes: 2

Michael Dillon
Michael Dillon

Reputation: 1037

Use a session variable to store the logged in user id. Once the session is established and your authentication scheme inserts the logged in flag you are all set. Just check the logged in flag when you need to perform any user requests.

Upvotes: 0

Germann Arlington
Germann Arlington

Reputation: 3353

Try to require more secure UUID identifiers (generated and stored by you) for such requests, they are still not completely secure but considerably better than simple ids

Upvotes: 0

Related Questions