Skip to content

Instantly share code, notes, and snippets.

@xxRockOnxx
Last active June 27, 2024 16:46
Show Gist options
  • Save xxRockOnxx/54fe4653145c2f0e8bf5a267e245bc1d to your computer and use it in GitHub Desktop.
Save xxRockOnxx/54fe4653145c2f0e8bf5a267e245bc1d to your computer and use it in GitHub Desktop.
Laravel Tinker: login as another user and generate an injectable session cookie

Generating session cookie

  1. Enter Laravel Tinker
php artisan tinker
  1. Authenticate
# Login using id
auth()->loginUsingId(1);

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

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()
  1. Generate the cookie value
\Illuminate\Cookie\CookieValuePrefix::create(config('session.cookie'), app(\Illuminate\Contracts\Encryption\Encrypter::class)->getKey()).session()->getId()
  1. Encrypt cookie value
app(\Illuminate\Contracts\Encryption\Encrypter::class)->encrypt(<value from previous step>, false)

# Or by using the helper:
encrypt(<value from previous step>, false)

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

It is highly likely the 2nd parameter here is always false for everyone.

If not, then you probably know what you are doing.

  1. urlencode it or simply just replace the = at the end with %3D
urlencode(<value from previous step>)
  1. 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

Code in single block

$email = "";

auth()->login(User::where('email', $email)->first())

session()->save()

$cookieValue = \Illuminate\Cookie\CookieValuePrefix::create(config('session.cookie'), app('encrypter')->getKey()).session()->getId()

$encryptedCookieValue = encrypt($cookieValue, false);

$encodedCookieValue = urlencode($encryptedCookieValue);

You could turn this into a command if desired.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment