We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Phalcon\Security\Exception: A dependency injection container is required to access the 'session' service

I was following the example today from https://forum.phalcon.io/discussion/4737/csrf-validation-does-not-work-on-remote-server and can someone explain what this error mean? It happened when I call $tokenKey = $security->getTokenKey(); and $token = $security->getToken(); in my ControllerBase.

Here is my Security.php:

    <?php

    use \Phalcon\DI;

    class Security extends \Phalcon\Security
    {
        public function getTokenKey($numberBytes = 13)
        {
            $key = '$PHALCON/CSRF/KEY$';

            $tokenKey = \Phalcon\DI::getDefault()->getShared('session')->get($key);

            if ($tokenKey)
            {
                return $tokenKey;
            }

            return parent::getTokenKey($numberBytes);
        }   

        public function getToken($numberBytes = 32)
        {
            $key = '$PHALCON/CSRF$';

            $token = \Phalcon\DI::getDefault()->getShared('session')->get($key);

            if ($token)
            {
                return $token;
            }

            return parent::getToken($numberBytes);
        } 

        public function changeToken($numberBytes = 32)
        {
            return parent::getToken($numberBytes);
        }

    }

And this is from my index.php:

// Security
$di->setShared('security', function() {
    $security = new Security();
    return $security;
});

// Session
$di->setShared('session', function() {
    $session = new \Phalcon\Session\Adapter\Files();
    $session->start();
    return $session;
});

The reason I am setting this up is because the checktoken() is invalidating me when I am following the way the documentation handles csrf token.



34.6k
Accepted
answer

I think you don't need to use: \Phalcon\DI::getDefault() because you have $this->getDi() there.

Also, if you pass false as the third parameter of checkToken() it does not invalidates the token when it's validated.

https://github.com/phalcon/cphalcon/blob/master/phalcon/security.zep#L341

I think I ran into the favicon problem as described in another thread somewhere in this forum. Anyways thanks alot.