Ad

JWT Cookie Is Not Stored Right - Laravel

- 1 answer

I am using Laravel 5.1 and i'm trying to implement a basic JWT-Auth logic.

While i'm creating the jwt_token right (i log it to laravel.log, token has it's three different parts divided by dot as expected), when i try to create a cookie with the jwt_token value, a completely different cookie is created, with no division by dots and it is much bigger than the original jwt_token.

I think code is pretty straightforward :

$jwt_token = $this->findOrCreateUser($user);
Log::error('My jwt_token is '. $jwt_token); //from the log here i see the right jwt_token

//i disable the http-only flag because i want to read it with js

return redirect('/index.html')->withCookie(Cookie::make('jwt_token',$jwt_token,1000,null,null,false,false));

I would be really glad, if anyone could give me some pointers about what may be wrong !

Thanks

Ad

Answer

Laravel 5.1 ships by default with a middleware named EncryptCookies that is registered in the global $middleware array of the HTTP kernel. So the cookies are automatically encrypted when sent to the browser, that's why your cookie value is not the plain text representation of your JWT token.

You can easily fix that in two ways:

1. Add the cookie name to the $except array in the App\Http\Middleware\EncryptCookies:

protected $except = [
    'jwt_token'
];

2. Comment/remove the EncryptCookies middleware in the App\Http\Kernel class (although I do not recommend this unless you specifically want all cookies to be unencrypted):

protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    // \App\Http\Middleware\EncryptCookies::class,
    \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    \App\Http\Middleware\VerifyCsrfToken::class,
];
Ad
source: stackoverflow.com
Ad