标签(空格分隔): 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']。 默认 ['']。
- 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
guide-rest-controllers