Skip to content

Instantly share code, notes, and snippets.

@igorw
Created December 17, 2013 16:18
Show Gist options
  • Save igorw/8007626 to your computer and use it in GitHub Desktop.
Save igorw/8007626 to your computer and use it in GitHub Desktop.
Using laravel 4.1 CookieGuard middleware with silex.

Encrypted Cookies

This is an example of using laravel 4.1 CookieGuard middleware with silex. This demonstrates the composability of stack middlewares.

All of the outgoing cookies are encrypted. If decryption of incoming cookies fails, the application will ignore them.

Installation

Just clone the gist and install the dependencies via composer.

$ composer install

Running it

You can use the PHP built-in webserver to run the example. Just type this into the console:

$ php -S localhost:8080 example.php

Then open http://localhost:8080 in your browser.

{
"require": {
"illuminate/cookie": "~4.1",
"silex/silex": "~1.1",
"stack/builder": "~1.0",
"stack/run": "~1.0"
}
}
<?php
use Illuminate\Encryption\Encrypter;
use Silex\Application;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Request;
require 'vendor/autoload.php';
// define silex app
$app = new Application();
$app->get('/', function (Request $request, Application $app) {
$username = $request->cookies->get('username');
return $username
? sprintf('Hi %s. <a href="/logout">logout</a>', $app->escape($username))
: '<a href="/login">login</a>';
});
$app->get('/login', function () {
return '<form method="post" action="/login"><input name="username"><input type="submit" value="login"></form>';
});
$app->post('/login', function (Request $request, Application $app) {
$username = $request->request->get('username');
$response = $app->redirect('/');
$response->headers->setCookie(new Cookie('username', $username));
return $response;
});
$app->get('/logout', function (Application $app) {
$response = $app->redirect('/');
$response->headers->clearCookie('username');
return $response;
});
// set up stack middlewares
$key = '18PuCX2tc6RIcWNf3Zfy';
$app = (new Stack\Builder())
->push('Illuminate\Cookie\Guard', new Encrypter($key))
->resolve($app);
// front controller
Stack\run($app);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment