I try to make a test REST API on yii2. The documentation lists three basic authentication methods. I decided to try HTTP Basic Auth. But there were problems and questions.

The documentation indicates that the controller should configure the behavior

use yii\filters\auth\HttpBasicAuth; public function behaviors() { $behaviors = parent::behaviors(); $behaviors['authenticator'] = [ 'class' => HttpBasicAuth::className(), ]; return $behaviors; } 

And after findIdentityByAccessToken() method, but where? In the example below for the class User

 use yii\db\ActiveRecord; use yii\web\IdentityInterface; class User extends ActiveRecord implements IdentityInterface { public static function findIdentityByAccessToken($token, $type = null) { return static::findOne(['access_token' => $token]); } } 

Well and moreover, it turns out that all this needs to be written in each controller for each model. And if there are 50? Duplicate the same thing so many times? How to be here? And what's wrong? And where to set up the findIdentityByAccessToken() method? Just need a general authorization for all API in one place

    1 answer 1

    In order not to copy it into all controllers, you can add an event in the application config and forbid using it all without authorization except for separate endpoints. Ready code for config / web.php:

     'as beforeRequest' => [ 'class' => yii\filters\AccessControl::className(), 'rules' => [ [ 'allow' => true, 'actions' => [ 'login', 'registration', ], ], [ 'allow' => true, 'roles' => ['@'], ], ], 'denyCallback' => function ($rule, $action) { throw new \yii\web\UnauthorizedHttpException('You are not allowed to access this page'); } ], 
    • and how then to log in? Turning to api, I must, in fact, pass an authorization key in the headers to requests, thereby signing each request. Or should we create a separate controller for authorization, send the data for the inputs, check and authorize? And then send nothing in the headers? - n.osennij
    • As you wish. You can use the standard approach with a cookie. Of course there will be an endpoint for the entrance, that is, for getting a cookie or a token. Cook, you too, roughly sign. - zabachok