REST API is working without authentication methods. Now i wanted to authenticate REST API with HTTP Basic authentication for API requests via mobile application. I tried with y
You need to set the token before saving the user. in the User model use this
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
if ($this->isNewRecord) {
$this->auth_key = Yii::$app->getSecurity()->generateRandomString();
}
return true;
}
return false;
}
now you have an auth_key for each user
to return the auth_key you need to add actionLogin in the UserController
public function actionLogin()
{
$post = Yii::$app->request->post();
$model = User::findOne(["email" => $post["email"]]);
if (empty($model)) {
throw new \yii\web\NotFoundHttpException('User not found');
}
if ($model->validatePassword($post["password"])) {
$model->last_login = Yii::$app->formatter->asTimestamp(date_create());
$model->save(false);
return $model; //return whole user model including auth_key or you can just return $model["auth_key"];
} else {
throw new \yii\web\ForbiddenHttpException();
}
}
after that, in each API request you send the auth_key in the header instead of sending username and password
$ curl -H "Authorization: Basic bd9615e2871c56ffffdd8b88b576f131f51c20f3bc" API_URL
to check if the auth_key is valid, define 'authenticator' in the UserController behaviors. (don't forget to to exclude 'create', 'login', 'resetpassword' from the authentication)
public function behaviors()
{
return ArrayHelper::merge(
parent::behaviors(), [
'authenticator' => [
'class' => CompositeAuth::className(),
'except' => ['create', 'login', 'resetpassword'],
'authMethods' => [
HttpBasicAuth::className(),
HttpBearerAuth::className(),
QueryParamAuth::className(),
],
],
]
);
}