我正在尝试遵循Yii2的身份验证教程*,但由于项目的要求,我需要构建自定义身份验证.虽然教程确实说明了你可以自己做,但没有详细说明如何.我需要创建哪些文件以及我需要添加到$ behavior ['authenticator']以指向我的自定义身份验证模块的位置和值?
*https://github.com/yiisoft/yii2/blob/master/docs/guide/rest-authentication.md
问题在当前状态下过于宽泛,但我会尝试提供基本算法.
创建从中扩展的类yii\filters\auth\AuthMethod.
在哪里放置它取决于你(因为使用命名空间),你可以遵循自己的约定.假设我们将其放在common\components文件夹中.
您必须至少实现authenticate方法AuthInterface(challenge并且handleFailure已经有默认实现,但您显然也可以覆盖它们).
namespace common\components;
use yii\filters\auth\AuthMethod;
class CustomAuth extends AuthMethod
{
/**
* @inheritdoc
*/
public function authenticate($user, $request, $response)
{
// Put your logic here
}
}
Run Code Online (Sandbox Code Playgroud)
REST控制器中的用法:
use common\components\CustomAuth;
...
/**
* @inheritdoc
*/
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => CustomAuth::className(),
];
return $behaviors;
}
Run Code Online (Sandbox Code Playgroud)
还看到内置的身份验证方法来实现(HttpBasicAuth,HttpBearerAuth,QueryParamAuth).