I\'m impressed with how simple it was to create a REST api in Yii2. However, i\'m having a little trouble understanding the Basic Authentication. My needs are utterly simp
Let's watch and try to understand "yii" way basic auth for REST.
1st. When you adding behavior to your REST controller, you enabling basic auth:
$behaviors['authenticator'] = [
'class' => HttpBasicAuth::className(),
];
As you did. What does it mean? It means that your application will parse your authorization header. It looks like:
Authorization : Basic base64(user:password)
Here is a trick for yii2. If you look at code more carefully, you will see that yii uses access_token
from user field, so your header should look like:
Authorization : Basic base64(access_token:)
You can parse this header by your own, if you want to change this behavior:
$behaviors['authenticator'] = [
'class' => HttpBasicAuth::className(),
'auth' => [$this, 'auth']
];
....
public function auth($username, $password)
{
return \app\models\User::findOne(['login' => $username, 'password' => $password]);
}
2nd thing to do. You must implement findIdentityByAccessToken()
function from identityInterface.
Why your IDE complaining?
class User extends ActiveRecord implements IdentityInterface
Here's how your user class declaration should look.
From your implementation and structure:
public static function findIdentityByAccessToken($token, $type = null)
{
return static::findOne(['access_token' => $token]);
}
you not returning object of class which implements identity interface.
How to make it properly?
Add column access_token to your users table, and return back your user model (you can look how it must look here - https://github.com/yiisoft/yii2-app-advanced/blob/master/common/models/User.php)
If you do this - default code will work with your findIdentityByAccessToken()
implementation.
If you don't want to add field to users table - make new one with user_id,access_token
fields. Then your implementation should look like:
public static function findIdentityByAccessToken($token, $type = null)
{
$apiUser = ApiAccess::find()
->where(['access_token' => $token])
->one();
return static::findOne(['id' => $apiUser->user_id, 'status' => self::STATUS_ACTIVE]);
}
Hope i could cover all of your questions.