PHPackages                             bicf/yii2-security-headers - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Security](/categories/security)
4. /
5. bicf/yii2-security-headers

ActiveYii2-extension[Security](/categories/security)

bicf/yii2-security-headers
==========================

Security oriented headers management

v1.2.1(4y ago)46.7k2GPL-2.0-onlyPHP

Since Sep 1Pushed 4y ago3 watchersCompare

[ Source](https://github.com/bicf/yii2-security-headers)[ Packagist](https://packagist.org/packages/bicf/yii2-security-headers)[ RSS](/packages/bicf-yii2-security-headers/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (1)Versions (13)Used By (0)

Yii2 headers security
=====================

[](#yii2-headers-security)

Introduction
-----------------------------------------------------

[](#introduction-)

Yii2 implementation of [CSP - Content Security Policy](https://www.w3.org/TR/CSP1/)

See also [MDN docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)

Installation
-----------------------------------------------------

[](#installation-)

Installation is recommended to be done via [composer](https://getcomposer.org/ "The PHP package manager") by running:

```
composer require bicf/yii2-security-headers "*"

```

Alternatively you can add the following to the `require` section in your `composer.json` manually:

```
{
"bicf/yii2-security-headers": "*"
}
```

Run `composer update` afterwards.

Then proceed to configuration.

Configuration
-------------------------------------------------------

[](#configuration-)

The version 1.1 is a Module implementation.

Module *securityHeader* sample configuration in main.php

```
[
    'bootstrap'=>[
        'securityHeader',
    ],
    'modules' => [
        'securityHeader' => [
            'class' => bicf\securityheaders\Module::class,
            'modules' => [
               'XContentTypeOptions'=>[
                   'class' => 'bicf\securityheaders\modules\HeaderXContentTypeOptions',
                   'value' => 'nosniff',
               ],
               'XFrameOptions'=>[
                   'class' => 'bicf\securityheaders\modules\HeaderXFrameOptions',
                   'value' => 'SAMEORIGIN',
               ],
               'AccessControlAllowMethods'=>[
                   'class' => 'bicf\securityheaders\modules\HeaderAccessControlAllowMethods',
                   'value' => 'GET',
               ],
               'AccessControlAllowOrigin'=>[
                   'class' => 'bicf\securityheaders\modules\HeaderAccessControlAllowOrigin',
                   'value' => 'https://api.example.com',
               ],
               'ContentSecurityPolicyAcl'=>[
                   'class' => 'bicf\securityheaders\modules\HeaderContentSecurityPolicyAcl',
                   'enabled' => false,
                   'policies' => [
                       'default-src' => "'self'",
                       'frame-src'   => "'self' www.facebook.com www.youtube.com www.google.com",
                       'img-src'     => "'self' www.google-analytics.com",
                       'font-src'    => "'self' fonts.gstatic.com maxcdn.bootstrapcdn.com",
                       'media-src'   => "'self'",
                       'script-src'  => "'self' www.google-analytics.com",
                       'style-src'   => "'self' maxcdn.bootstrapcdn.com",
                        'connect-src' => "'self'",
                        'report-uri'  => "/report-csp-acl",
                    ],
                ],
                'ContentSecurityPolicyMonitor'=>[
                    'class' => 'bicf\securityheaders\modules\HeaderContentSecurityPolicyMonitor',
                    'policies' => [
                        'default-src' => "'self'",
                        'frame-src'   => "'self' www.facebook.com www.youtube.com www.google.com",
                        'img-src'     => "'self' www.google-analytics.com",
                        'font-src'    => "'self' fonts.gstatic.com maxcdn.bootstrapcdn.com",
                        'media-src'   => "'self'",
                        'script-src'  => "'self' www.google-analytics.com",
                        'style-src'   => "'self' maxcdn.bootstrapcdn.com",
                        'connect-src' => "'self'",
                        'report-uri'  => "/report-csp-acl",
                    ],
                ],
            ],
        ],
    ],

    'components' => [
        // components stuff
        // no need to add anything
    ],
]
```

Yii2 integration of Content Security Policy Header
==================================================

[](#yii2-integration-of-content-security-policy-header)

Possible integrations
---------------------

[](#possible-integrations)

CSP can work by **signature** or by the **nonce token**see:

Integration by signature
------------------------

[](#integration-by-signature)

Done simply adding the signatures to CSP configuration

Example:

```
'style-src'   => "'sha256-aqNNdDLnnrDOnTNdkJpYlAxKVJtLt9CtFLklmInuUAE=' 'sha256-6fwFCXmgb6H4XQGajtDSVG3YuKmX3dT1NkX4+z510Og=' 'sha256-ZdHxw9eWtnxUb3mk6tBS+gIiVUPE3pGM470keHPDFlE='",
```

This kind of integration does not require patch to the framework code but it's space wasting and hard to mantain even with a small number of signatures.

Integration by nonce token
--------------------------

[](#integration-by-nonce-token)

This kind of integration require some (small) patch at framework (\\yii\\helpers\\BaseHtml) level to take full advantage of nonce token. The nonce feature (enabled by default) don't need maintenace once integrated and has reduced footprint on the header

Here follow the patched versions of BaseHtml functions to support the nonce parameter in a transparent way.

**Patch to Html::script helper**

The patched *\\yii\\helpers\\BaseHtml::script()* :

```
    public static function script($content, $options = [])
    {
        if(Yii::$app->response instanceof SecureRequestInterface){
            $behavior = Yii::$app->response->getBehavior(SecureRequestInterface::CSP_NONCE_BEHAVIOR);
            if($behavior != null){
                $options = array_merge(Yii::$app->response->getContentSecurityPolicyTokenArray(),$options );
            }
        }
        return static::tag('script', $content, $options);
    }
```

**Tag script required by the project Assets**

The patched *\\yii\\helpers\\BaseHtml::jsFile()* :

```
    public static function jsFile($url, $options = [])
    {
        $options['src'] = Url::to($url);
        if (isset($options['condition'])) {
            $condition = $options['condition'];
            unset($options['condition']);
            return self::wrapIntoCondition(static::tag('script', '', $options), $condition);
        }

        if(Yii::$app->response instanceof SecureRequestInterface){
            $behavior = Yii::$app->response->getBehavior('cspBehavior');
            if($behavior != null){
                $options = array_merge(Yii::$app->response->getContentSecurityPolicyTokenArray(),$options );
            }
        }

        return static::tag('script', '', $options);
    }
```

or (better?) call *script* funtion inside *jsFile* function:

```
    public static function jsFile($url, $options = [])
    {
        $options['src'] = Url::to($url);
        if (isset($options['condition'])) {
            $condition = $options['condition'];
            unset($options['condition']);
            return self::wrapIntoCondition(static::tag('script', '', $options), $condition);
        }

        return static::script('', $options);
    }
```

A different approach for `` the views
---------------------------------------------

[](#a-different-approach-for-script-the-views)

**Tag script inside the views**

When the `` is explicit used in view or controllers the solution is to add the nonce parameter directly in the tag by:

`Yii::$app->response->getContentSecurityPolicyTokenAttribute()`

**Inside a view**

```
getContentSecurityPolicyTokenAttribute();?> >
    alert("test");

```

**A patched** `\yii\debug\Module::renderToolbar` **function**

```
    /**
     * Renders mini-toolbar at the end of page body.
     *
     * @param \yii\base\Event $event
     */
    public function renderToolbar($event)
    {
        if (!$this->checkAccess() || Yii::$app->getRequest()->getIsAjax()) {
            return;
        }

        /* @var $view View */
        $view = $event->sender;
        echo $view->renderDynamic('return Yii::$app->getModule("' . $this->id . '")->getToolbarHtml();');

        // echo is used in order to support cases where asset manager is not available
        echo '' . $view->renderPhpFile(__DIR__ . '/assets/toolbar.css') . '';
        echo '' . $view->renderPhpFile(__DIR__ . '/assets/toolbar.js') . '';
    }
```

In detail the line:

```
echo '' . $view->renderPhpFile(__DIR__ . '/assets/toolbar.js') . '';
```

Runtime disabilitation
----------------------

[](#runtime-disabilitation)

Since no header is sent until the `render` call it's possible to disable one or more modules as needed.

```
public function actionIndex() {
    Yii::$app->getResponse()->modules['sample-module']->enabled=false;
    return $this->render("index");
}
```

Legacy Implementation
----------------------------------------------------------------------

[](#legacy-implementation-)

This is the old implementation, extending the Request Class.

> **IMPORTANT:** If you don't setup your configuration no header will be sent.

An example of configuration:

```
[
    'components' => [
        'response' => [
            'class' => 'bicf\securityheaders\components\Response',
            'on afterPrepare' => ['bicf\securityheaders\components\Response','addSecurityHeaders'],
            'modules' => [
               'XContentTypeOptions'=>[
                   'class' => 'bicf\securityheaders\modules\HeaderXContentTypeOptions',
                   'value' => 'nosniff',
               ],
               'AccessControlAllowMethods'=>[
                   'class' => 'bicf\securityheaders\modules\HeaderAccessControlAllowMethods2',
                   'value' => 'GET',
               ],
               'AccessControlAllowOrigin'=>[
                   'class' => 'bicf\securityheaders\modules\HeaderAccessControlAllowOrigin',
                   'value' => 'https://api.example.com',
               ],
               'ContentSecurityPolicyAcl'=>[
                   'class' => 'bicf\securityheaders\modules\HeaderContentSecurityPolicyAcl',
                   'enabled' => false,
                   'policies' => [
                       'default-src' => "'self'",
                       'frame-src'   => "'self' www.facebook.com www.youtube.com www.google.com",
                       'img-src'     => "'self' www.google-analytics.com",
                       'font-src'    => "'self' fonts.gstatic.com maxcdn.bootstrapcdn.com",
                       'media-src'   => "'self'",
                       'script-src'  => "'self' www.google-analytics.com",
                       'style-src'   => "'self' maxcdn.bootstrapcdn.com",
                        'connect-src' => "'self'",
                        'report-uri'  => "/report-csp-acl",
                    ],
                ],
                'ContentSecurityPolicyMonitor'=>[
                    'class' => 'bicf\securityheaders\modules\HeaderContentSecurityPolicyMonitor',
                    'policies' => [
                        'default-src' => "'self'",
                        'frame-src'   => "'self' www.facebook.com www.youtube.com www.google.com",
                        'img-src'     => "'self' www.google-analytics.com",
                        'font-src'    => "'self' fonts.gstatic.com maxcdn.bootstrapcdn.com",
                        'media-src'   => "'self'",
                        'script-src'  => "'self' www.google-analytics.com",
                        'style-src'   => "'self' maxcdn.bootstrapcdn.com",
                        'connect-src' => "'self'",
                        'report-uri'  => "/report-csp-acl",
                    ],
                ],
            ],
        ],
    ],
]
```

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity27

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity69

Established project with proven stability

 Bus Factor1

Top contributor holds 66.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~120 days

Recently: every ~228 days

Total

12

Last Release

1489d ago

Major Versions

0.1.4.2 → v1.0.02020-05-06

### Community

Maintainers

![](https://www.gravatar.com/avatar/d95bc0a79be7fdb26b1dc45f029dbff06d2df7b1648bb5af5428795baacb8b40?d=identicon)[bicf](/maintainers/bicf)

---

Top Contributors

[![bicf](https://avatars.githubusercontent.com/u/478974?v=4)](https://github.com/bicf "bicf (24 commits)")[![ivan-redooc](https://avatars.githubusercontent.com/u/11387801?v=4)](https://github.com/ivan-redooc "ivan-redooc (11 commits)")[![deepsourcebot](https://avatars.githubusercontent.com/u/60907429?v=4)](https://github.com/deepsourcebot "deepsourcebot (1 commits)")

---

Tags

yii2

### Embed Badge

![Health badge](/badges/bicf-yii2-security-headers/health.svg)

```
[![Health](https://phpackages.com/badges/bicf-yii2-security-headers/health.svg)](https://phpackages.com/packages/bicf-yii2-security-headers)
```

###  Alternatives

[nickcv/yii2-encrypter

Openssl Encrypter for Yii2

19640.0k1](/packages/nickcv-yii2-encrypter)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
