Search code examples
laravellaravel-8laravel-echo

Laravel Identity User without revealing ID to the user


In laravel I've set a privatechannel for websocket broadcasting.

The channel is this:

Broadcast::channel('user.{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
});

So in this case I am revealing the user's ID to them as a part of the authentication process.

Does Laravel have any other unique user identifier I could use that does not leak user count info to the user?

For example:

Broadcast::channel('user.{token}', function ($user, $token) {
    return $user->some_unique_token === $token;
});

Or should I just use something like https://hashids.org/php/ to obfuscate the user ID? (not sure if Laravel ships with something like this?)


Solution

  • In the end I just created a simple hash method for the user model and then used this instead of the ID to validate the user.

    This was the method added to user model:

    public function hash(){
        return hash('sha256',$this->id.env('APP_KEY'));
    }
    

    Then broadcast channel goes like this:

    Broadcast::channel('user.{hash}', function ($user, $hash) {
        return $user->hash() === $hash;
    });