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

Content Security Policy

Hey guys,

want to share my plugin which adds Content-Security-Policy support. Content Security Policy allows us to prevent xss attacks by specifying trusted origins, so browsers won't load unexpected scripts, styles, frames, etc.

The plugin also provides assets manager class which automatically whitelists all origins of outputted scripts and styles.

Here is a simple example:

<?php

// services.php file

use Phalcon\Plugin\CSP\ContentSecurityPolicy;

// register CSP service
$di->set( 'csp', function() {
    $csp = new ContentSecurityPolicy();
    return $csp;
}, true );

// register Assets Manager class
$di->set( 'assets', function() {
    $manager = new \Phalcon\Plugin\CSP\Assets\Manager();
    return $manager;
}, true );
<?php

// public/index.php

// register application and add CSP to event manager
try {
    $csp = $di->getShared( 'csp' );

    $eventsManager = new \Phalcon\Events\Manager();
    $eventsManager->attach( 'application:beforeSendResponse', $csp );

    $application = new \Phalcon\Mvc\Application($di);
    $application->setEventsManager( $eventsManager );

    $response = $application->handle();
    $response->send();
} catch (\Exception $e) {
    echo $e->getMessage();
}
<?php

// IndexController.php file

use Phalcon\Plugin\CSP\ContentSecurityPolicy as CSP;

class IndexController extends \Phalcon\Mvc\Controller {

    public function indexAction() {
        // whitelist Google fonts origin
        $this->csp->addPolicy( CSP::DIRECTIVE_FONT_SRC, 'https://fonts.gstatic.com' );
    }

}

Could you please check it out and let me know what you think about it? https://github.com/eugene-manuilov/phalcon-csp

How to do it with multi module? please help