REST API to login on Yii2

I am starting to use yii2 and I am providing REST Apifrom a web application. I could not find the documentation on how to provide login functions using yii2 REST api. Previously yii1, we had an action called actionLoginthat enters the username and password and authenticates it (using the user model). Is this the same approach still with yii2? As in UserController(under the Api module), is there a method actionLoginwith a GET request type and after successful authentication returns User object(with an access token for subsequent calls?)?

+4
source share
2 answers

Well, it looks like creating an actionLogin method that accepts a username and password is still a continuation of yii2 (confirmed by the yii2 developers). In addition, you need to either exclude the actionLogin action from the authentication behavior, and there are several ways to execute it (either override it before the action or not call the authentication method, and another approach is to add this actionLogin method to some controller that does not describe the authentication behavior) .

+1
source

I implemented it as follows:

config / web.php file

    'user' => [
        'identityClass' => 'app\models\User',
        'enableSession' => false,
        'loginUrl' => null,
        //'enableAutoLogin' => false,
    ],

Then I changed the User identity model

class User extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{
    ....

    public static function findIdentityByAccessToken($token, $type = null)
    {
        return static::findOne(['access_token' => $token]);
    }

    public function updateAccessToken()
    {
        $this->access_token = Yii::$app->security->generateRandomString();
        $this->last_visit_time = date('Y-m-d H:i:s', strtotime('now'));
        //$this->last_login_ip = Yii::$app->request->userIP;
        $this->save();
    }

    public function getId()
    {
        return $this->id;
    }

    public function getAuthKey()
    {
        //return $this->auth_key;
    }

    public function validateAuthKey($authKey)
    {
        //return $this->getAuthKey() === $authKey;
    }
    ...
}

Until I arrived, because after I do not know which controller I should use (if UserControlleror SiteController)

0
source

Source: https://habr.com/ru/post/1544209/


All Articles