Skip to content

Commit

Permalink
sample Twig deployment
Browse files Browse the repository at this point in the history
  • Loading branch information
alexweissman committed Aug 15, 2016
1 parent 3b4f432 commit bffa719
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,53 @@ $app->post('/api/myEndPoint',function ($req, $res, $args) {
$app->run();
```

### Accessing the token pair in templates (Twig, etc)

In many situations, you will want to access the token pair without needing to go through the request object. In these cases, you can use `getTokenName()` and `getTokenValue()` directly on the `Guard` middleware instance. This can be useful, for example in a [Twig extension](http://twig.sensiolabs.org/doc/advanced.html#creating-an-extension):

```php
class CsrfExtension extends \Twig_Extension
{

/**
* @var \Slim\Csrf\Guard
*/
protected $csrf;

public function __construct(\Slim\Csrf\Guard $csrf)
{
$this->csrf = $csrf;
}

public function getGlobals()
{
// CSRF token name and value
$csrfNameKey = $this->csrf->getTokenNameKey();
$csrfValueKey = $this->csrf->getTokenValueKey();
$csrfName = $this->csrf->getTokenName();
$csrfValue = $this->csrf->getTokenValue();

return [
'csrf' => [
'keys' => [
'name' => $csrfNameKey,
'value' => $csrfValueKey
],
'name' => $csrfName,
'value' => $csrfValue
]
];
}
}
```

Once you have registered your extension, you may access the token pair in any template:

```twig
<input type="hidden" name="{{csrf.keys.name}}" value="{{csrf.name}}">
<input type="hidden" name="{{csrf.keys.value}}" value="{{csrf.value}}">
```

## Handling validation failure

By default, `Slim\Csrf\Guard` will return a Response with a 400 status code and
Expand Down

0 comments on commit bffa719

Please sign in to comment.