Setting a secure remember me cookie in Laravel

folder_openLaravel, PHP, Technology
commentNo Comments

As of Laravel 5.0 it’s still not possible to set the remember me cookie with a secure flag. This despite the fact that there is a configuration option for secure session cookies

Fortunately modifying Laravel to set a secure log-in cookie is not difficult at all.

First we need to provide a custom Guard class for the Auth driver which overrides the setRecaller() method.

<?php 
/*  
 * Custom guard class that sets a secure log-in cookie.
 */ 
class SecureGuard extends \Illuminate\Auth\Guard
{
	/**
	 * Create a secure remember me cookie for a given ID.
	 *
	 * @param  string  $value
	 * @return \Symfony\Component\HttpFoundation\Cookie
	 */
	protected function createRecaller($value)
	{
		return $this->getCookieJar()->forever($this->getRecallerName(), $value, null, null, true);
	}
}

Now that we have our custom guard class we need to tell Laravel to use this new class. While not completely intuitive the best way to do that is to configure a custom auth driver where we wrap the default EloquentUserProvider class in our new SecureGuard class. Add the following to your global.php file.

<?php
/*
|--------------------------------------------------------------------------
| Auth Driver
|--------------------------------------------------------------------------
|
| Extend the auth driver to support secure cookies.
|
*/

Auth::extend('SecureAuth', function($app)
{
	$model    = $app['config']['auth.model'];
	$provider = new Illuminate\Auth\EloquentUserProvider($app['hash'], $model);

	return new SecureGuard($provider, $app['session.store']);
});

Finally update your auth.php config file to set the new auth driver.

'driver' => 'SecureAuth',

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.