4
votes

I am starting to use yii2 and I am providing a REST Api from the web app. I could not find any documentation on how to provide login functionality using yii2 REST api. Previously in yii1, we used to have an action called actionLogin which takes in a username and password and authenticate it(with User model). Is that the same approach still with yii2? Like in UserController(under the Api module) have an actionLogin method with GET request type and once authenticated successfully return User object(with access token for subsequent calls?) ?

2

2 Answers

1
votes

Well, it looks like creating an actionLogin method and that takes in username and password is still the way to go on yii2 (confirmed from yii2 developers). Also, you have to either exclude the actionLogin from authentication behaviors and there are couple of ways it could be done(either through override before action and not calling authenticate method, and the other approach is to add this actionLogin method in some controller which does not describe the authentication behavior).

0
votes

I implemented it following:

config/web.php file

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

Then I modified the model User identity

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 over there I arrived, because after I don't know which is the controller that I should using (if UserController or SiteController)