我正在 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
动词就像在这个例子中:
这同样适用于在 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 操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!