Yii2 Restful 跨域調用 - CORS 過濾器

標簽(空格分隔): Yii2


1 CORS 簡介

跨域資源共享(Cross-origin resource sharing CORS)允許一個網站從其他域(domain) 請求資源。

正常情況下,由于同源安全策略(same origin security policy),跨域資源訪問請求(cross-domain resourse requests) 會被瀏覽器禁止。CORS 定義了一種 Browser和 Server 協同來決定是否允許跨域請求。

2 Yii2 實現 CORS

2.1 使用默認設置

yii\filters\Cors 過濾器可以用來幫助 Yii2 配置是否允許跨域請求。
Cors 過濾器必須在 Authentication / Authorization filters之前,保證 CORS headers 總是被發送給瀏覽器。

在Controller 中添加如下代碼即可

use yii\filters\auth\HttpBasicAuth;

public function behaviors()
{
    $behaviors = parent::behaviors();

    // remove authentication filter
    $auth = $behaviors['authenticator'];
    unset($behaviors['authenticator']);
    
    // add CORS filter
    $behaviors['corsFilter'] = [
        'class' => \yii\filters\Cors::className(),
    ];
    
    // re-add authentication filter
    $behaviors['authenticator'] = $auth;
    // avoid authentication on CORS-pre-flight requests (HTTP OPTIONS method)
    $behaviors['authenticator']['except'] = ['options'];

    return $behaviors;
}


上面代碼將使用默認 $cors 設置。

$cors 默認值

public $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' => [],
    ];

1. cors['Origin']: 允許的源. [''] (所有都允許) 或者 ['http://www.myserver.net', 'http://www.myotherserver.com']。 默認 ['']。

  1. cors['Access-Control-Request-Method']: 允許的動詞,比如 ['GET', 'OPTIONS', 'HEAD']. 默認 ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']。
  2. cors['Access-Control-Request-Headers']: 允許的請求頭。 [''] 所有請求頭都允許或者具體指定 ['X-Request-With'].默認[''].
  3. cors['Access-Control-Allow-Credentials']: 是否允許使用 credentials。 允許的值 true, false or null ,默認 null.
  4. cors['Access-Control-Max-Age']: pre-flight 請求的生命周期。默認 86400.**

2.2 使用自定義設置

Cors 過濾器可以使用$cors屬性來調整響應頭。

代碼

public function behaviors()
{
    return [
        'corsFilter' => [
            'class' => \yii\filters\Cors::className(),
            'cors' => [
                // restrict access to
                'Origin' => ['http://www.myserver.com', 'https://www.myserver.com'],
                'Access-Control-Request-Method' => ['POST', 'PUT'],
                // Allow only POST and PUT methods
                'Access-Control-Request-Headers' => ['X-Wsse'],
                // Allow only headers 'X-Wsse'
                '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'],
            ],

        ],
    ];
}

2.3 為特定 action 設置響應頭

可以使用 $actions 屬性為特定 action 調整 CORS 響應頭,她會覆蓋 $cors 上的相同設置。比如為 actionLogin 添加 Control-Allow-Credentials
代碼

 

public function behaviors()
{
    return ArrayHelper::merge([
        [
            'class' => Cors::className(),
            'cors' => [
                'Origin' => ['http://www.myserver.net'],
                'Access-Control-Request-Method' => ['GET', 'HEAD', 'OPTIONS'],
            ],
            'actions' => [
                'login' => [
                    'Access-Control-Allow-Credentials' => true,
                ]
            ]
        ],
    ], parent::behaviors());
}

3 參考

[Cors][1]
[1]: http://www.yiiframework.com/doc-2.0/guide-structure-filters.html#cors

guide-rest-controllers

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 標簽(空格分隔): Yii2 1 什么是CORS CORS是一個W3C標準,全稱是"跨域資源共享"(Cross-o...
    ahcj_11閱讀 9,533評論 0 1
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,991評論 19 139
  • 跨域資源共享 CORS 詳解 1 簡介 CORS需要瀏覽器和服務器同時支持。目前,所有瀏覽器都支持該功能,IE瀏覽...
    _小分隊閱讀 2,076評論 2 4
  • CORS是一個W3C標準,全稱是"跨域資源共享"(Cross-origin resource sharing)。 ...
    起名字太累閱讀 958評論 0 2
  • 本周的作業是使用記賬APP記賬一周,我使用隨手記已經記賬了快一個月,驚嘆之余更多的是感慨,以前從來沒有這么系統的記...
    趙聆希閱讀 251評論 0 0