YII2 rest guide http basic auth

public $enableCsrfValidation = false;

/**
* enable session false tidak di perlukan untuk rest
*/
public function init() {
parent::init();
\Yii::$app->xxx->enableSession = false;
}

pastikan anda memasang session false dan csrf validation false untuk rest api

untuk extends \yii\rest\Controller  gunakan ini jika anda tidak menuliskannya , secara default YII2 akan menggunakan \yii\web\Controller , CMIIW

public static function allowedDomains() {
return [// '*', // star allows all domains
// 'http://test1.example.com',
// 'http://test2.example.com',
];
}

jika anda mengakses dengan ajax , pastikan anda melakukan set ini agar tidak terkena cors

public function behaviors() {
$behaviors = parent::behaviors();

$behaviors['corsFilter'] = [
'class' => Cors::className(),
'cors' => [
// restrict access to
'Origin' => static::allowedDomains(),
// 'Origin' => '*',
// Allow only POST and PUT methods
'Access-Control-Request-Method' => [
'GET',
'POST',
'PUT',
'PATCH',
'DELETE',
'HEAD',
'OPTIONS'
],
// Allow only headers 'X-Wsse'
'Access-Control-Request-Headers' => [
'*'
],
// Allow credentials (cookies, authorization headers, etc.) to be exposed to the browser
'Access-Control-Allow-Credentials' => true,
// Allow OPTIONS caching
'Access-Control-Max-Age' => 3600,
// Allow the X-Pagination-Current-Page header to be exposed to the browser.
'Access-Control-Expose-Headers' => [
'X-Pagination-Current-Page'
]
]
];
$behaviors['authenticator'] = [
'class' => HttpBasicAuth::className(),
'except' => [
'signup',
],
'auth' => [
$this,
'auth'
]
];
$behaviors['access'] = [
'class' => 'mdm\admin\components\AccessControl',
'allowActions' => [
'signup',
]
];
$behaviors['verbs'] = [
'class' => VerbFilter::className(),
'actions' => [
'view' => ['get'],
]
];

return $behaviors;
}

/**
* menghilangkan csrf validation karena bukan post , tidak di gunakan untuk rest
*/
public function beforeAction($action) {

$this->enableCsrfValidation = false;
// header("access-control-allow-origin: *");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

if (!parent::beforeAction($action)) {
return false;
}
return true;

// return parent::beforeAction($action);
}

/**
* after action selalu menyimpan ke dalam tabel log
*/
public function afterAction($action, $result) {
$result = parent::afterAction($action, $result);

$log = new Log();
$log->request = json_encode(Yii::$app->getRequest()->getRawBody());
$log->respon = json_encode($result);
$log->keterangan_log = "user rest";
$log->action = $action->id;
$log->save();
return $result;
// return $log->id_log;
}

/**
* function untuk athentikasi username dan password
*/
public function auth($username, $password) {
$user = xxx::find()->where([
'username' => $username,
'status_id_status' => "4"
])->one();

if ($user instanceof \app\models\xxx) {
if (Yii::$app->getSecurity()->validatePassword($password, $user->password_hash)
Yii::$app->xxx->login($user);
return $user;
} else {
throw new UnauthorizedHttpException('Password and Hash not same.');
}
} else {

throw new UnauthorizedHttpException('You are requesting with an invalid credential.');
}
}

Leave a Reply

© 2021 IT & Photography blog | WordPress Theme : ScrollMe