[Solved]: Trouble upgrading to slim/csrf 0.8


#1

I’ve been using slim/csrf 0.5 for ages now and never had a problem. While reviewing my composer.json I noticed that now 0.8.2 is available so I changed the version referenced in my composer.json to “^0.8”.

After upgrading, now none of my forms manage to pass the CSRF validation stage. Here is the code I’m using:

  1. dependencies.php

    $container['csrf'] = function($container) {
       $guard = new \Slim\Csrf\Guard();
       $guard->setFailureCallable(function($request, $response, $next) {
           $request = $request->withAttribute("csrf_status", false);
           return $next ($request, $response);
       });
    
       return $guard;
    };
    
  2. In my Twig extension I’m using the following functions which I then call in my template:

     private $csrf;
    
     public function __construct ($container)
     {
         parent::__construct($container);
         $this->csrf = $container->get('csrf');
     }
    
     public function csrfName () : string
     {
         return $this->csrf->getTokenName();
     }
    
     public function csrfTokenName () : string
     {
         return $this->csrf->getTokenNameKey();
     }
    
     public function csrfValue () : string
     {
         return $this->csrf->getTokenValue();
     }
    
     public function csrfTokenValue () : string
     {
         return $this->csrf->getTokenValueKey();
     }
    
  3. In my form processing code I’m calling:

     $request->getAttribute('csrf_status');
    

Now, the odd thing is that the csrf_status property is never populated in the request, so the call from #3 always return null (the default).

Also, while my templates are generating seemingly valid csrf tokens, the token names/values never make it to the CSRF storage.

I’ve been staring at this for a while now and I’m drawing a blank. Does anybody see what I’m doing wrong here? I’m guessing that I’m overlooking something totally stupid, but so far it escapes me.

Thanks :slight_smile:


#2

Figured it out, apparently my brain was too tired to follow instructions. I failed to do a

$slimGuard->validateStorage();

For reference, my initialization code in dependencies.php now looks like this:

 $container['csrf'] = function($container) {
    $guard = new \Slim\Csrf\Guard();
    $guard->validateStorage();
    $guard->setFailureCallable(function($request, $response, $next) {
        $request = $request->withAttribute("csrf_status", false);
        return $next ($request, $response);
    });

    return $guard;
};