简体   繁体   中英

Best practice of writing custom authentication mechanism on Yii2

I need to write a very specific authentication for my web application. There is API on the side which accepts login + password pair and returns the result (and, a token). I don't want to store any login information on the Yii2 side besides a login token i've got from API. And this must be the only way i auth my clients (so i don't use OAuth-like application).

What is the best practive to override "classic" code in Yii2? Just use filters and modify User model? Example:

First, i recieve a token and save it somewhere for a session:

$token = GatewayAPI::login($user, $password);

Then, every internal request i do will look like this:

$result = GatewayAPI::addPosition($token, $data);

So, i don't have any database to work with, just cache and memory. Almost everything is handled on API side.

My task is to implement login check - if token is recieved from API - then it's considered as a success. And to store that token for use within current session (probably in memcache, it must not be opened to public).

As a matter of fact Yii2 does not require login/password anywhere. You don't need to modify or extend User model if you mean \\yii\\web\\User . You need to create your own class implementing IdentityInterface and set this class as userIdentity in your config components->user->identityClass :

[
    'components' => [
        'user' => [
            'class' => 'yii\web\User', // not necessary, this is by default
            'identityClass' => 'my\namespace\User' 
        ]
    ]
] 

There are 5 methods in the interface and they are not about login/pass. This class of yours may store in your db everything you want. For example you may copy any of popular user modules to your project, remove everything related to storing and searching by login/pass from that User model and add your API functionality - and it will work.

UPD. Your added functionality will look like this:

$token = GatewayAPI::login($user, $password);
$user = \my\namespace\User::findOne(['token' => $token]);
Yii::$app->user->login($user);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM