Class yii\filters\Cors

Inheritanceyii\filters\Cors » yii\base\ActionFilter » yii\base\Behavior » yii\base\BaseObject
Implementsyii\base\Configurable
Available since version2.0
Source Code https://github.com/yiisoft/yii2/blob/master/framework/filters/Cors.php

Cors filter implements Cross Origin Resource Sharing.

Make sure to read carefully what CORS does and does not. CORS do not secure your API, but allow the developer to grant access to third party code (ajax calls from external domain).

You may use CORS filter by attaching it as a behavior to a controller or module, like the following,

public function behaviors()
{
    return [
        'corsFilter' => [
            'class' => \yii\filters\Cors::className(),
        ],
    ];
}

The CORS filter can be specialized to restrict parameters, like this, MDN CORS Information

public function behaviors()
{
    return [
        'corsFilter' => [
            'class' => \yii\filters\Cors::className(),
            'cors' => [
                // restrict access to
                'Origin' => ['http://www.myserver.com', 'https://www.myserver.com'],
                // Allow only POST and PUT methods
                'Access-Control-Request-Method' => ['POST', 'PUT'],
                // Allow only headers 'X-Wsse'
                'Access-Control-Request-Headers' => ['X-Wsse'],
                // Allow credentials (cookies, authorization headers, etc.) to be exposed to the browser
                'Access-Control-Allow-Credentials' => true,
                // Allow OPTIONS caching
                'Access-Control-Max-Age' => 3600,
                // Allow the X-Pagination-Current-Page header to be exposed to the browser.
                'Access-Control-Expose-Headers' => ['X-Pagination-Current-Page'],
            ],

        ],
    ];
}

For more information on how to add the CORS filter to a controller, see the Guide on REST controllers.

Public Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
$actions array Define specific CORS rules for specific actions yii\filters\Cors
$cors array Basic headers handled for the CORS requests. yii\filters\Cors
$except array List of action IDs that this filter should not apply to. yii\base\ActionFilter
$only array List of action IDs that this filter should apply to. yii\base\ActionFilter
$owner yii\base\Component|null The owner of this behavior yii\base\Behavior
$request yii\web\Request The current request. yii\filters\Cors
$response yii\web\Response The response to be sent. yii\filters\Cors

Public Methods

Hide inherited methods

MethodDescriptionDefined By
__call() Calls the named method which is not a class method. yii\base\BaseObject
__construct() Constructor. yii\base\BaseObject
__get() Returns the value of an object property. yii\base\BaseObject
__isset() Checks if a property is set, i.e. defined and not null. yii\base\BaseObject
__set() Sets value of an object property. yii\base\BaseObject
__unset() Sets an object property to null. yii\base\BaseObject
addCorsHeaders() Adds the CORS headers to the response. yii\filters\Cors
afterAction() This method is invoked right after an action is executed. yii\base\ActionFilter
afterFilter() yii\base\ActionFilter
attach() {@inheritdoc} yii\base\ActionFilter
beforeAction() {@inheritdoc} yii\filters\Cors
beforeFilter() yii\base\ActionFilter
canGetProperty() Returns a value indicating whether a property can be read. yii\base\BaseObject
canSetProperty() Returns a value indicating whether a property can be set. yii\base\BaseObject
className() Returns the fully qualified name of this class. yii\base\BaseObject
detach() {@inheritdoc} yii\base\ActionFilter
events() Declares event handlers for the $owner's events. yii\base\Behavior
extractHeaders() Extract CORS headers from the request. yii\filters\Cors
hasMethod() Returns a value indicating whether a method is defined. yii\base\BaseObject
hasProperty() Returns a value indicating whether a property is defined. yii\base\BaseObject
init() Initializes the object. yii\base\BaseObject
overrideDefaultSettings() Override settings for specific action. yii\filters\Cors
prepareHeaders() For each CORS headers create the specific response. yii\filters\Cors

Protected Methods

Hide inherited methods

MethodDescriptionDefined By
getActionId() Returns an action ID by converting yii\base\Action::$uniqueId into an ID relative to the module. yii\base\ActionFilter
headerize() Convert any string (including php headers with HTTP prefix) to header format. yii\filters\Cors
headerizeToPhp() Convert any string (including php headers with HTTP prefix) to header format. yii\filters\Cors
isActive() Returns a value indicating whether the filter is active for the given action. yii\base\ActionFilter
prepareAllowHeaders() Handle classic CORS request to avoid duplicate code. yii\filters\Cors

Property Details

$actions public property

Define specific CORS rules for specific actions

public array $actions = []
$cors public property

Basic headers handled for the CORS requests.

public array $cors = ['Origin' => ['*'], 'Access-Control-Request-Method' => ['GET''POST''PUT''PATCH''DELETE''HEAD''OPTIONS'], 'Access-Control-Request-Headers' => ['*'], 'Access-Control-Allow-Credentials' => null'Access-Control-Max-Age' => 86400'Access-Control-Expose-Headers' => []]
$request public property

The current request. If not set, the request application component will be used.

public yii\web\Request $request null
$response public property

The response to be sent. If not set, the response application component will be used.

Method Details

addCorsHeaders() public method

Adds the CORS headers to the response.

public void addCorsHeaders ( $response, $headers )
$response yii\web\Response
$headers array

CORS headers which have been computed

beforeAction() public method

{@inheritdoc}

public void beforeAction ( $action )
$action
extractHeaders() public method

Extract CORS headers from the request.

public array extractHeaders ( )
return array

CORS headers to handle

headerize() protected method

Convert any string (including php headers with HTTP prefix) to header format.

Example:

  • X-PINGOTHER -> X-Pingother
  • X_PINGOTHER -> X-Pingother
protected string headerize ( $string )
$string string

String to convert

return string

The result in "header" format

headerizeToPhp() protected method

Convert any string (including php headers with HTTP prefix) to header format.

Example:

  • X-Pingother -> HTTP_X_PINGOTHER
  • X PINGOTHER -> HTTP_X_PINGOTHER
protected string headerizeToPhp ( $string )
$string string

String to convert

return string

The result in "php $_SERVER header" format

overrideDefaultSettings() public method

Override settings for specific action.

public void overrideDefaultSettings ( $action )
$action yii\base\Action

The action settings to override

prepareAllowHeaders() protected method

Handle classic CORS request to avoid duplicate code.

protected void prepareAllowHeaders ( $type, $requestHeaders, &$responseHeaders )
$type string

The kind of headers we would handle

$requestHeaders array

CORS headers request by client

$responseHeaders array

CORS response headers sent to the client

prepareHeaders() public method

For each CORS headers create the specific response.

public array prepareHeaders ( $requestHeaders )
$requestHeaders array

CORS headers we have detected

return array

CORS headers ready to be sent