Reputation: 2422
I'm trying to follow the authentication tutorial* for Yii2 but due to the project's requirements I need to build custom authentication. Although the tutorial does state you can make your own it doesn't elaborate on how. What files do I need to create and where and what values do I need to add to $behaviors['authenticator'] to refer to my custom auth module?
*https://github.com/yiisoft/yii2/blob/master/docs/guide/rest-authentication.md
Upvotes: 3
Views: 3106
Reputation: 33548
The question is too broad in current state, but I will try to provide the basic algorithm.
Create class extending from yii\filters\auth\AuthMethod
.
Where to place it it's up to you (because of using namespaces), you can follow your own convention. Let's say we place it in common\components
folder.
You must at least implement authenticate
method of AuthInterface
(challenge
and handleFailure
already have default implementations, but you can obviously override them too).
namespace common\components;
use yii\filters\auth\AuthMethod;
class CustomAuth extends AuthMethod
{
/**
* @inheritdoc
*/
public function authenticate($user, $request, $response)
{
// Put your logic here
}
}
Usage in REST controller:
use common\components\CustomAuth;
...
/**
* @inheritdoc
*/
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => CustomAuth::className(),
];
return $behaviors;
}
Also see how built-in auth methods are implemented (HttpBasicAuth
, HttpBearerAuth
, QueryParamAuth
).
Upvotes: 6