Skip to content

Instantly share code, notes, and snippets.

@james2doyle
Last active November 23, 2022 19:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save james2doyle/53c29871f92136767ed464931f82c8bc to your computer and use it in GitHub Desktop.
Save james2doyle/53c29871f92136767ed464931f82c8bc to your computer and use it in GitHub Desktop.
Console command to generate a valid session cookie for a authenticated user in a Laravel app
<?php
declare(strict_types=1);
use App\Models\User;
use Illuminate\Support\Facades\Artisan;
use Symfony\Component\HttpFoundation\Cookie;
use Illuminate\Cookie\CookieValuePrefix;
Artisan::command('user-cookie', function (): void {
/** @var User */
$user = User::where('email', 'user@laravel.com')->firstOrFail();
/** @var \Illuminate\Auth\SessionGuard */
$guard = auth()->guard('web');
$guard->getSession()->start();
$guard->login($user);
// persist this session so the id is valid
$guard->getSession()->save();
$name = $guard->getSession()->getName();
$data = $guard->getSession()->getId();
$config = config('session');
$expires = now()->add('minutes', env('SESSION_LIFETIME'))->timestamp;
/** @var \Illuminate\Encryption\Encrypter */
$encrypter = $guard->getSession()->getEncrypter();
// assumes that the cookies are encrypted
$value = $encrypter->encrypt(
CookieValuePrefix::create($name, $encrypter->getKey()) . $data,
false // do not serialize
);
$cookie = new Cookie(
$name, $value, $expires,
$config['path'], $config['domain'], $config['secure'], false, false, $config['same_site'] ?? null
);
/**
* @psalm-suppress InvalidScope
*/
$this->comment(sprintf('%s', $cookie));
})->purpose('Display a valid cookie for a user');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment