標簽(空格分隔): Yii2
1 CORS 簡介
跨域資源共享(Cross-origin resource sharing CORS)允許一個網(wǎng)站從其他域(domain) 請求資源。
正常情況下,由于同源安全策略(same origin security policy),跨域資源訪問請求(cross-domain resourse requests) 會被瀏覽器禁止叨吮。CORS 定義了一種 Browser和 Server 協(xié)同來決定是否允許跨域請求。
2 Yii2 實現(xiàn) CORS
2.1 使用默認設置
yii\filters\Cors 過濾器可以用來幫助 Yii2 配置是否允許跨域請求。
Cors 過濾器必須在 Authentication / Authorization filters之前糊闽,保證 CORS headers 總是被發(fā)送給瀏覽器邢锯。
在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']谊囚。 默認 ['']怕享。
- cors['Access-Control-Request-Method']: 允許的動詞,比如 ['GET', 'OPTIONS', 'HEAD']. 默認 ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']镰踏。
- cors['Access-Control-Request-Headers']: 允許的請求頭函筋。 [''] 所有請求頭都允許或者具體指定 ['X-Request-With'].默認[''].
- cors['Access-Control-Allow-Credentials']: 是否允許使用 credentials。 允許的值 true, false or null 奠伪,默認 null.
- 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