I am learning angular and in the process found this tutorial series (part1, part2) which integrates Yii and Angular.
Unfortunately, I was coming up against some problems. I could request data from API unless auth was required. I was getting errors relating to preflight checks when trying to submit auth and it turns out Yii’s CORS filter was not letting the request through.
After much trial and error and reading issues/pull requests on github I decided to extend the yii2 core Cors.php class based on this PR. File attached.
I use it like this:
<?php
namespace frontend\controllers;
use Yii;
use common\models\LoginForm;
use common\models\User;
use yii\rest\ActiveController;
use yii\web\Response;
use yii\filters\auth\HttpBearerAuth;
use yii\filters\contentNegotiator;
use yii\filters\AccessControl;
use common\components\Cors;
class ApiController extends ActiveController
{
public $modelClass='common\models\User';
public function behaviors() {
$behaviors = parent::behaviors();
$behaviors['corsFilter'] = [
'class' => Cors::className(),
'cors' => [
'Origin' => ['*'],
//'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
'Access-Control-Request-Headers' => ['Origin', 'X-Requested-With', 'Content-Type', 'accept', 'Authorization'],
//'Access-Control-Allow-Credentials' => true,
//'Access-Control-Max-Age' => 86400,
//'Access-Control-Expose-Headers' => [],
//'Access-Control-Request-Headers' => ['Expiry'],
],
];
$behaviors['authenticator'] = [
'class' => HttpBearerAuth::className(),
'only' => ['dashboard'],
];
$behaviors['contentNegotiator'] = [
'class' => ContentNegotiator::className(),
'formats' => [
'application/json' => Response::FORMAT_JSON,
],
];
$behaviors['access'] = [
'class' => AccessControl::className(),
'only' => ['dashboard'],
'rules' => [
[
'actions' => ['dashboard'],
'allow' => true,
'roles' => ['@'],
],
],
];
return $behaviors;
}
public function actionLogin()
{
$model = new LoginForm();
if ($model->load(Yii::$app->getRequest()->getBodyParams(), '') && $model->login()) {
return ['access_token' => Yii::$app->user->identity->getAuthKey()];
} else {
$model->validate();
return $model;
}
}