Yii2 过滤器
过滤器AccessController
AccessControl 基于一组规则提供简单的访问控制
/**
* {@inheritdoc}
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::class,
'only'=>['index'],
'rules' => [
//任何人都可以访问index
[
'actions'=>['index'],
'allow'=>true,
'roles'=>['?']
],
//指定IP游客可以访问view
[
'actions'=>['view'],
'allow'=>true,
'ips'=>[
'192.168.*',
'10.13.1.182'
],
'roles'=>['?']
],
//登录用户可以访问update
[
'actions'=>['update'],
'allow'=>true,
'roles'=>['@']
],
//登录用户需要post访问update
[
'actions'=>['update'],
'allow'=>true,
'roles'=>['@'],
'verbs'=>['post']
],
//指定日期可以访问test
[
'actions'=>['test'],
'allow' => true,
'matchCallback'=>function($rule,$action){
return date('d-m') === '11-11';
}
],
]
],
];
}
参数说明
actions: 设置哪个动作匹配此规则。
roles: 设定哪个角色匹配此规则。
*: 任何用户,包括匿名和验证通过的用户。
?: 匿名用户。
@: 验证通过的用户。
ips: 设定哪个客户端IP匹配此规则。
verbs: 设定哪种请求类型(例如:GET, POST)匹配此规则。
matchCallback:指定一个PHP回调,以确定应用该规则。
denyCallback:PHP回调,当规则禁止访问的时候会被调用。
过滤器VerbFilter
VerbFilter 是一个操作过滤器它通过 HTTP 请求方法进行过滤
public function behaviors()
{
return [
'verbs' => [
'class' => \yii\filters\VerbFilter::className(),
'actions' => [
'index' => ['GET'],
'view' => ['GET'],
'create' => ['GET', 'POST'],
'update' => ['GET', 'PUT', 'POST'],
'delete' => ['POST', 'DELETE'],
],
],
];
}
过滤器 AjaxFilter
AjaxFilter 只允许限制 Ajax 请求的访问
public function behaviors()
{
return [
[
'class' => 'yii\filters\AjaxFilter',
'only' => ['index']
],
];
}
过滤器 corsFilter
允许开发人员授予对第三方代码的访问权限(来自外部域的 Ajax 调用)
public function behaviors()
{
return [
'corsFilter' => [
'class' => \yii\filters\Cors::className(),
'cors' => [
// restrict access to
'Origin' => ['http://www.myserver.com', 'https://www.myserver.com'],
// Allow only POST and PUT methods
'Access-Control-Request-Method' => ['POST', 'PUT'],
// Allow only headers 'X-Wsse'
'Access-Control-Request-Headers' => ['X-Wsse'],
// Allow credentials (cookies, authorization headers, etc.) to be exposed to the browser
'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'],
],
],
];
}
标签:actions,Access,Allow,过滤器,POST,Yii2,true
From: https://www.cnblogs.com/hu308830232/p/18105471