Hi.
Im trying to implement CSRF and adding the hidden fields using csrf.field inside the twig file. having some difficulty. Not sure if this is the best effective way in doing this. If you have a better way, please share
Your help will be appreciated. Thanks
Getting empty values, the error, dump within Twig
" <input type="hidden" name="csrf_name" value=""> <input type="hidden" name="csrf_value" value=""> "
add CSRF to middleware.
$app->add(new CsrfViewMiddleware($container));
The Guard class gets added to the container interface
Guard::class => function (ContainerInterface $c) {
return new Guard();
},
the class CsrfViewMiddleware
namespace Ti\Middleware;
use Slim\Csrf\Guard;
class CsrfViewMiddleware extends Middleware
{
public function __invoke($request, $response, $next) {
$this->view()->getEnvironment()->addGlobal('csrf', ['field' => '
<input type="hidden" name="' . $this->guard()->getTokenNameKey() . '" value="' . $this->guard()->getTokenName() . '">
<input type="hidden" name="' . $this->guard()->getTokenValueKey() . '" value="' . $this->guard()->getTokenValue() . '">
',]);
return $next($request, $response);
}
}
the class Middleware
namespace Ti\Middleware;
use Ti\Support\Auth\Auth;
use Slim\Csrf\Guard;
use Slim\Views\Twig;
class Middleware {
protected $container;
public function __construct($container) {
$this->container = $container;
}
protected function view() {
return $this->container->get(Twig::class);
}
protected function guard() {
return $this->container->get(Guard::class);
}
protected function router() {
return $this->container->get('router');
}
}
the CsrftestController class with render testcsrf/testcsrf
namespace Ti\Controllers;
class CsrftestController extends BaseController
{
public function get()
{
// return $this->view($this->response,'testcsrf/testcsrf');
return $this->render('testcsrf/testcsrf');
}
public function post()
{
return 'test csrf post... after update button was pressed';
}
}
Twig file with csrf.field testing dump
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSRF</title>
</head>
<body>
<form action="{{ path_for('csrfpost') }}" method="post">
<h4> This test csrf... if you refresh page it will give error... (Not allowed to refresh page)</h4>
</br> </br> </br>
<button type="submit">Update</button>
{{ dump(csrf.field | raw) }}
// {{ csrf.field | raw}}
</form>
</body>
</html>