在yii 开发中一个项目内实现多个不同的user Auth 认证
首先把不需要此认证的模块控制器过滤掉
public function behaviors() { return [ 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ '*' => ['POST'], ], ], 'bearerAuth' => [ 'class' => UserAuth::className(), 'except' => [ 'carray/*', 'sys/login', ], 'exceptModules' => true ] ]; }
新建一个认证 ; 重写authenticate;
重新定义identityClass
在需要的模块或者模型中重新写入
behaviors;
/** * {@inheritDoc} */ public function authenticate($user, $request, $response) { $authHeader = $request->getHeaders()->get($this->header); if ($authHeader !== null) { if ($this->pattern !== null) { if (preg_match($this->pattern, $authHeader, $matches)) { $authHeader = $matches[1]; } else { return null; } } Yii::$app->user->identityClass = MemberModel::className(); $identity = $user->loginByAccessToken($authHeader, get_class($this)); if ($identity === null) { $this->challenge($response); $this->handleFailure($response); } return $identity; } return null; }