DEV Community

Lemuel Flores
Lemuel Flores

Posted on

Laravel Tinker: login as another user and generate an injectable session cookie

Generating session cookie

  • Enter Laravel Tinker
php artisan tinker
Enter fullscreen mode Exit fullscreen mode
  • Authenticate
# Login using id
auth()->loginUsingId(1);

# Login using a user instance
auth()->login(User::where('email', 'foo@bar.com')->first())
Enter fullscreen mode Exit fullscreen mode
  • Save the session
session()->save()
Enter fullscreen mode Exit fullscreen mode

If you are not using EncryptedCookie for some reason, you can stop at this step and proceed to injecting the session id to your session cookie:

session()->getId()
Enter fullscreen mode Exit fullscreen mode
  • Generate the cookie value that is about to get encrypted
\Illuminate\Cookie\CookieValuePrefix::create(config('session.cookie'), app(\Illuminate\Contracts\Encryption\Encrypter::class)->getKey()).session()->getId()
Enter fullscreen mode Exit fullscreen mode
  • Generate the encrypted cookie value

It is highly likely the 2nd parameter here is always false for everyone. If not, then you probably know what you are doing.

Here is the reference: https://github.com/laravel/framework/blob/v11.7.0/src/Illuminate/Cookie/Middleware/EncryptCookies.php#L187-L189

app(\Illuminate\Contracts\Encryption\Encrypter::class)->encrypt(<value from previous step>, false)
Enter fullscreen mode Exit fullscreen mode
  • urlencode it or simply just replace the = at the end with %3D
urlencode(<value from previous step>)
Enter fullscreen mode Exit fullscreen mode
  • You can now proceed to injecting the generated string to the browser

Injecting session cookie to the browser

  • Open your website e.g http://localhost
  • Open devtools
  • Open Application tab
  • Open Storage > Cookies > your website (e.g http://localhost)
  • Double click on the value column of the session cookie (e.g laravel_session)
  • Paste the value from Generate step
  • Refresh the page

Top comments (0)