Yii2 REST API authentication

2020-03-08 06:20发布

问题:

I was looking for tutorials and read yii's official tutorial about REST API and authentication, but I just can't figure it out how to authenticate user via REST API. How to configure it. I'm using Yii 2.0.1 advanced template. I've been trying to do it, but I'm not sure if I'm doing it right and what's the right way of authenticating user.

Below is my code and it returns correct data. But I'm not sure if it is the right way. Because In another controller I need to check if user is logged in to access actions.

<?php
namespace api\modules\backend\controllers;

use yii\rest\ActiveController;
use yii\filters\auth\CompositeAuth;
use yii\filters\auth\HttpBasicAuth;
use yii\filters\auth\HttpBearerAuth;
use yii\filters\auth\QueryParamAuth;

use Yii;
use dektrium\user\models\LoginForm;
use dektrium\user\models\User;

class UserController extends ActiveController
{
    public $modelClass = "dektrium\user\models\User";

    public function actionLogin()
    {
        $model = new LoginForm;

        if ($model->load(\Yii::$app->getRequest()->post()) && $model->login()) {
            //return $this->goBack();
             echo \Yii::$app->user->identity->getAuthKey();
            //echo json_encode(['a'=>Yii::$app->user->getId()]);
        }

    }

  public function actionIndexx()
    {
        if (\Yii::$app->user->isGuest) {
            throw new \HttpHeaderException();
        }
        echo \Yii::$app->user->getId();
    }

}
?>

回答1:

I think login process will be more or less same. Only Url structure is different when you use REST API, but what you do in actions is up to you. Any where in you application you can check if user is logged in or not with this code:

\Yii::$app->user->isGuest

It will return true if user is NOT logged in otherwise false.

And if you need to restrict access to actions then you can use Access Control Filter or Role Based Access Control

Again I think Access Control Filter implementation should be same even for REST API.



标签: rest yii2