I’m getting 401 and CORS if I use the following code and try the api from browser - ajax call. My controller is extended from Controller. As I understood Browser send options header which API doesn’t allow unless it has authorization header.
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => HttpBearerAuth::className(),
];
// remove authentication filter
$auth = $behaviors['authenticator'];
unset($behaviors['authenticator']);
// add CORS filter
$behaviors['corsFilter'] = [
'class' => \yii\filters\Cors::className(),
];
// re-add authentication filter
$behaviors['authenticator'] = $auth;
// avoid authentication on CORS-pre-flight requests (HTTP OPTIONS method)
$behaviors['authenticator']['except'] = ['options'];
return $behaviors;
}
As soon I add this
if(\Yii::$app->getRequest()->getMethod()!=‘OPTIONS’){
$behaviors[‘authenticator’] = [
‘class’ => HttpBearerAuth::className(),
];
}
I don’t get any error. The above code allowing preflight but is there any security risk??