add api authentication
This commit is contained in:
57
frontend/modules/api/controllers/UserController.php
Normal file
57
frontend/modules/api/controllers/UserController.php
Normal file
@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace frontend\modules\api\controllers;
|
||||
|
||||
use common\models\User;
|
||||
use frontend\modules\api\models\LoginForm;
|
||||
use Yii;
|
||||
use yii\filters\ContentNegotiator;
|
||||
use yii\rest\ActiveController;
|
||||
use yii\helpers\ArrayHelper;
|
||||
use yii\filters\auth\QueryParamAuth;
|
||||
use yii\web\BadRequestHttpException;
|
||||
use yii\web\Response;
|
||||
|
||||
class UserController extends ActiveController
|
||||
{
|
||||
public $modelClass = User::class;
|
||||
|
||||
public function behaviors()
|
||||
{
|
||||
return ArrayHelper::merge(parent::behaviors(), [
|
||||
[
|
||||
'class' => ContentNegotiator::class,
|
||||
'formats' => [
|
||||
'application/json' => Response::FORMAT_JSON,
|
||||
],
|
||||
],
|
||||
'authenticatior' => [
|
||||
'class' => QueryParamAuth::class, //implement access token authentication
|
||||
'except' => ['login'], // no need to verify the access token method, pay attention to distinguish between $noAclLogin
|
||||
]
|
||||
]);
|
||||
}
|
||||
|
||||
public function actions()
|
||||
{
|
||||
$action = parent::actions(); // TODO: Change the autogenerated stub
|
||||
unset($action['index']);
|
||||
unset($action['create']);
|
||||
unset($action['update']);
|
||||
unset($action['delete']);
|
||||
}
|
||||
|
||||
|
||||
public function actionLogin()
|
||||
{
|
||||
$model = new LoginForm();
|
||||
if ($model->load(Yii::$app->getRequest()->getBodyParams(), '') && $model->login()) {
|
||||
return [
|
||||
'access_token' => $model->login(),
|
||||
];
|
||||
} else {
|
||||
throw new BadRequestHttpException(json_encode($model->errors));
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user