1. <small id='YX4Jo'></small><noframes id='YX4Jo'>

        <legend id='YX4Jo'><style id='YX4Jo'><dir id='YX4Jo'><q id='YX4Jo'></q></dir></style></legend>
        <tfoot id='YX4Jo'></tfoot>
        <i id='YX4Jo'><tr id='YX4Jo'><dt id='YX4Jo'><q id='YX4Jo'><span id='YX4Jo'><b id='YX4Jo'><form id='YX4Jo'><ins id='YX4Jo'></ins><ul id='YX4Jo'></ul><sub id='YX4Jo'></sub></form><legend id='YX4Jo'></legend><bdo id='YX4Jo'><pre id='YX4Jo'><center id='YX4Jo'></center></pre></bdo></b><th id='YX4Jo'></th></span></q></dt></tr></i><div id='YX4Jo'><tfoot id='YX4Jo'></tfoot><dl id='YX4Jo'><fieldset id='YX4Jo'></fieldset></dl></div>
          <bdo id='YX4Jo'></bdo><ul id='YX4Jo'></ul>

      2. Yii2 CORS with Auth 不适用于非 CRUD 操作

        时间:2023-10-16

        • <i id='1QNye'><tr id='1QNye'><dt id='1QNye'><q id='1QNye'><span id='1QNye'><b id='1QNye'><form id='1QNye'><ins id='1QNye'></ins><ul id='1QNye'></ul><sub id='1QNye'></sub></form><legend id='1QNye'></legend><bdo id='1QNye'><pre id='1QNye'><center id='1QNye'></center></pre></bdo></b><th id='1QNye'></th></span></q></dt></tr></i><div id='1QNye'><tfoot id='1QNye'></tfoot><dl id='1QNye'><fieldset id='1QNye'></fieldset></dl></div>
            <tbody id='1QNye'></tbody>
            • <bdo id='1QNye'></bdo><ul id='1QNye'></ul>
              <legend id='1QNye'><style id='1QNye'><dir id='1QNye'><q id='1QNye'></q></dir></style></legend>

                  <small id='1QNye'></small><noframes id='1QNye'>

                • <tfoot id='1QNye'></tfoot>
                • 本文介绍了Yii2 CORS with Auth 不适用于非 CRUD 操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

                  问题描述

                  我正在 Yii2 中构建 API 并添加了 CORS 和身份验证.这适用于所有创建/读取/更新/删除操作,但不适用于自定义操作.有没有人遇到过这种情况?

                  网址管理器:

                  ['class' =>'yii
                  estUrlRule', '控制器' =>'api/v1/user', 'pluralize' =>错误的],

                  控制器行为:

                  公共函数行为(){返回 ArrayHelper::merge(['corsFilter' =>['类' =>Cors::className(),],['类' =>HttpBearerAuth::className(),'除了' =>['选项','登录',],],], 父::行为());}

                  如前所述,CRUD 的操作很好,但是诸如 http://domain.com/user/test 之类的自定义操作将使用 401 Unauthorised 响应进行响应.

                  不能让 CORS 和 auth 一起处理自定义操作吗?

                  我应该补充一点,仅当浏览器发出 OPTIONS 请求时才会出现问题 (401).正常请求(curl、Postman)不受影响.问题似乎出现在 RESTful、Cors、Auth 组合中.

                  解决方案

                  试试这个:

                  公共函数行为(){$behaviors = parent::behaviors();未设置($behaviors['authenticator']);$behaviors['corsFilter'] = ['类' =>Cors::className(),'cors' =>['起源' =>['*'],访问控制请求方法"=>['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],'访问控制请求头' =>['*'],'访问控制-允许-凭据' =>真的,],];$behaviors['authenticator'] = ['类' =>HttpBearerAuth::className(),'除了' =>['选项','登录'],];返回 $behaviors;}

                  它将取消设置由authenticator/Controller.php#L46" rel="nofollow noreferrer">父控制器 以确保首先处理 cors.然后我们强制 cors 在实现您自己的 authenticator 之前允许凭据.

                  <小时>

                  可能引发 Unauthorized 错误的另一件事是未找到或错误的 Options 响应,因为浏览器首先请求它获取允许的动词列表.您可以在浏览器的网络选项卡中的标头响应中检查该列表.

                  一般规则是,当您要求浏览器对任何 url 执行诸如 PUT、DELETE 或 POST 之类的明智动词时,它可能首先向同一个 url 发送 OPTIONS 请求> (检查 this) 以在发送实际请求之前检查该动词是否被允许.所以 Yii 应该被配置为通过执行正确的重定向来响应所有这些 OPTIONS 动词.

                  ActiveController 实现的默认 CRUD 操作正在使用那些 默认模式:

                  'PUT,PATCH {id}' =>'更新','删除 {id}' =>'删除','GET,HEAD {id}' =>'看法','POST' =>'创建','GET,HEAD' =>'指数','{id}' =>'选项','' =>'选项',

                  因此,无论您在 urlManager['rules'] 中实施了何种配置,请务必不要覆盖其中的最后 2 个,并且如果您使用自定义模式,请务必记住包含其等效的 options 动词就像在这个例子中:

                  <预><代码>['类' =>'yii estUrlRule','控制器' =>['帐户' =>'身份验证/帐户'],'模式' =>['POST,HEAD 登录' =>'登录','POST,HEAD 注册' =>'报名','POST req-reset-pass' =>'请求密码重置','POST 重置通过' =>'重设密码',//选项动词'选项登录' =>'选项','选项注册' =>'选项','OPTIONS req-reset-pass' =>'选项','选项重置通过' =>'选项',]],

                  这同样适用于在 extraPatterns 中添加自定义模式.

                  <小时>

                  Options 操作默认在 ActiveController 中实现.它的代码可以在这里看到.如果你扩展了一个不同于 ActiveController 的控制器,比如 yii estController 一定要手动包含它:

                  公共函数操作(){$actions = parent::actions();$actions['options'] = ['类' =>'yii
                  estOptionsAction',//选修的:'collectionOptions' =>['GET', 'POST', 'HEAD', 'OPTIONS'],'资源选项' =>['GET', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],];返回 $actions;}

                  I am building an API in Yii2 and have added CORS and authentication. This works fine for all Create/Read/Update/Delete actions but not for custom actions. Has anyone experienced this before?

                  URL manager:

                  ['class' => 'yii
                  estUrlRule', 'controller' => 'api/v1/user', 'pluralize' => false],
                  

                  Controller behaviors:

                  public function behaviors()
                  {
                      return ArrayHelper::merge([
                              'corsFilter' => [
                                  'class' => Cors::className(),
                              ],
                              [
                                  'class' => HttpBearerAuth::className(),
                                  'except' => ['options',
                                               'login',
                                  ],
                              ],
                          ], parent::behaviors()
                      );
                  }
                  

                  As mentioned, actions for CRUD are fine but a custom action such as http://domain.com/user/test will respond with a 401 Unauthorised response.

                  Is it not possible to get CORS and auth to work together on custom actions?

                  Edit: I should add that the issue (401) occurs only when a browser makes the OPTIONS request. Normal requests (curl,Postman) are not affected. The issue seems to occur with the RESTful,Cors,Auth combination.

                  解决方案

                  try this:

                  public function behaviors()
                  {
                      $behaviors = parent::behaviors();
                  
                      unset($behaviors['authenticator']);
                  
                      $behaviors['corsFilter'] = [
                          'class' => Cors::className(),
                          'cors' => [
                              'Origin' => ['*'],
                              'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
                              'Access-Control-Request-Headers' => ['*'],
                              'Access-Control-Allow-Credentials' => true,
                          ],
                      ];
                  
                      $behaviors['authenticator'] = [
                          'class' =>  HttpBearerAuth::className(),
                          'except' => ['options','login'],
                      ];
                  
                      return $behaviors;
                  }
                  

                  It will unset the default authenticator implemented by the parent controller to be sure that cors is treated first. Then we force cors to allow credentials before implementing your own authenticator.


                  The other thing that may raise that Unauthorized error is a not-found or wrong Options response as a browser request it first to get a list of allowed verbs. You may check that list in its headers response within your browser's network tab.

                  The general rule is when you ask your browser to perform a sensible verb like PUT, DELETE or POST to any url it may first send an OPTIONS request to that same url (check this) to check if that verb is allowed before sending the real request. So Yii should be configured to respond to all those OPTIONS verbs by performing the correct redirections.

                  The default CRUD actions implemented by ActiveController are using those default patterns:

                  'PUT,PATCH {id}' => 'update',
                  'DELETE {id}' => 'delete',
                  'GET,HEAD {id}' => 'view',
                  'POST' => 'create',
                  'GET,HEAD' => 'index',
                  '{id}' => 'options',
                  '' => 'options',
                  

                  So whatever configurations you did implement in urlManager['rules'] be sure to not override the last 2 of them and if you are using custom patterns always remember to include its equivalent options verbs like in this example:

                  [
                      'class' => 'yii
                  estUrlRule', 
                      'controller' => ['account' => 'auth/account'], 
                      'patterns' => [
                          'POST,HEAD login'  => 'login',
                          'POST,HEAD signup' => 'signup',
                          'POST req-reset-pass' => 'request-password-reset',
                          'POST reset-pass' => 'reset-password',
                          // OPTTIONS VERBS
                          'OPTIONS login' => 'options',
                          'OPTIONS signup' => 'options',
                          'OPTIONS req-reset-pass' => 'options',
                          'OPTIONS reset-pass' => 'options',
                      ]
                  ],
                  

                  The same applies when adding custom patterns within extraPatterns.


                  The Options action is implemented by default in ActiveController. it's code can be seen here. In case you are extending a different controller than ActiveController like maybe yii estController be sure to manually include it:

                  public function actions() 
                  {
                      $actions = parent::actions();
                      $actions['options'] = [
                          'class' => 'yii
                  estOptionsAction',
                          // optional:
                          'collectionOptions' => ['GET', 'POST', 'HEAD', 'OPTIONS'],
                          'resourceOptions' => ['GET', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
                      ];
                      return $actions;
                  }
                  

                  这篇关于Yii2 CORS with Auth 不适用于非 CRUD 操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

                  上一篇:Yii2 QueryBuilder 更新与加入 下一篇:Yii2:根据相关表中的另一个字段自动填充字段

                  相关文章

                    <legend id='6s3g3'><style id='6s3g3'><dir id='6s3g3'><q id='6s3g3'></q></dir></style></legend>

                  1. <tfoot id='6s3g3'></tfoot>

                    <i id='6s3g3'><tr id='6s3g3'><dt id='6s3g3'><q id='6s3g3'><span id='6s3g3'><b id='6s3g3'><form id='6s3g3'><ins id='6s3g3'></ins><ul id='6s3g3'></ul><sub id='6s3g3'></sub></form><legend id='6s3g3'></legend><bdo id='6s3g3'><pre id='6s3g3'><center id='6s3g3'></center></pre></bdo></b><th id='6s3g3'></th></span></q></dt></tr></i><div id='6s3g3'><tfoot id='6s3g3'></tfoot><dl id='6s3g3'><fieldset id='6s3g3'></fieldset></dl></div>
                    1. <small id='6s3g3'></small><noframes id='6s3g3'>

                        <bdo id='6s3g3'></bdo><ul id='6s3g3'></ul>