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,550评论 0 1
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,225评论 19 139
  • 跨域资源共享 CORS 详解 1 简介 CORS需要浏览器和服务器同时支持。目前,所有浏览器都支持该功能,IE浏览...
    _小分队阅读 2,078评论 2 4
  • CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)。 ...
    起名字太累阅读 963评论 0 2
  • 本周的作业是使用记账APP记账一周,我使用随手记已经记账了快一个月,惊叹之余更多的是感慨,以前从来没有这么系统的记...
    赵聆希阅读 257评论 0 0