Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

dizonb's avatar

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']);

});
0 likes
9 replies
tykus's avatar

The token determines the authenticated user for the current Request - the logged in User is a misnomer.

dizonb's avatar

@tykus Probably, I didn't explain it very well. I'm still trying out a solution I found in google. Gates or Policies. I'll try it out.

tykus's avatar

@dizonb Gates and/or Policies determine what the authenticated user can do - if you have the wrong authenticated user (based on the token used), then they will offer no protection.

dizonb's avatar

@tykus I have one scenario in my app where Friendship::table that contains user1_id and user2_id must be deleted. Only the user_id that is logged in or present in the current token must have the ability to delete that record. In my current app, other user deletes that record.

dizonb's avatar

(Edit) - Question updated above.

I'll check back tomorrow. Thanks.

tykus's avatar

@dizonb where are you protecting this Controller action to ensure an authenticated user?

dizonb's avatar

@tykus It's in the sanctum middleware. I'll try Policies today.

dizonb's avatar
dizonb
OP
Best Answer
Level 1

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.