slimphp / Slim-Csrf

Slim Framework CSRF protection middleware
MIT License
336 stars 58 forks source link

Automatically set CSRF value in middleware #40

Closed dewey92 closed 8 years ago

dewey92 commented 8 years ago
$app->add(function ($req, $res, $next) {
    $nameKey  = $this->csrf->getTokenNameKey();
    $valueKey = $this->csrf->getTokenValueKey();

    $this->view['csrf_key_name']      = $nameKey;
    $this->view['csrf_value_name']    = $valueKey;
    $this->view['csrf_key_content']   = $req->getAttribute($nameKey);
    $this->view['csrf_value_content'] = $req->getAttribute($valueKey);

    return $next($req, $res);
});

When I place the code in the middleware, only the first 2 lines that have value while $req->getAttribute($nameKey) and $req->getAttribute($valueKey) return empty. But,, they work when $req is in the context of app route.

Is there any way to make this work so that I don't need to write those 4 lines in every route? Thanks

schnittstabil commented 8 years ago

@dewey92 Why did you close this?

dewey92 commented 8 years ago

Already found the answer on https://github.com/slimphp/Slim-Csrf/issues/33 :+1:

aurmil commented 8 years ago

just in case: https://github.com/aurmil/slim3-csrf-utilities

alexweissman commented 8 years ago

Is there an official solution for this? I am trying to populate my hidden fields via global variables set in a Twig helper, and it appears that they are empty when I try to grab them from the request:

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

        return array(
            'site'   => $this->services->config['site'],
            'assets' => $this->services->assets,
            'csrf'   => [
                'keys' => [
                    'name'  => $csrfNameKey,
                    'value' => $csrfValueKey
                ],
                'name'  => $csrfName,
                'value' => $csrfValue
            ]
        );
    }

My keys are indeed set, but not the name or value.