The token determines the authenticated user for the current Request - the logged in User is a misnomer.
Protect api routes using JWT or Sanctum by Associated User_ID only
I'm logging in as a verified user in my simple application. However, when I postman the api routes with another token from another user, I can manipulate the records in the database. How to prevent other user manipulates the data?
Problem: Other users can perform operations even though they are not associated in the current request.
Goal: Only the user with the token and have the same id in the user_id in friend table must perform CRUD operations.
Controller
public function cancelRequest(FriendRequest $request)
{
$friend = Friend::where('user_id', $request->user_id)->where('friend_id', $request->friend_id);
if($friend->exists())
{
$friend->delete();
return response()->json([
'message'=>'Friend request successfully deleted!'
]);
}
}
api.php
Route::group(['middleware' => ['auth:sanctum'], 'as' => 'api.'], function() {
Route::group(['middleware' => 'verified'], function()
{
Route::post('/cancel-request', [FriendController::class, 'cancelRequest']);
});
Route::post('/logout', [AuthController::class, 'logout']);
});
I just ended up with
if(auth('sanctum')->user()->id == $request->user_id)
{
// cancel request logic
}
I don't know if it's the proper way. This code will I use for now. Any ideas are welcome. I'll just set my own comment as Best Answer.
Please or to participate in this conversation.