Ho sviluppato il servizio angolare & Yii2 REST. Hai problemi nel dominio incrociato. Qui di seguito aggiungo il mio angolare & Codice REST Yii2.YII REST + Angular Cross Domain CORS
AngularJs: (come 'http://organization1.example.com', 'http://organization2.example.com', ....)
$http.defaults.useXDomain = true;
$http.defaults.withCredentials = true;
$http.defaults.headers.common['Authorization'] = 'Bearer ' + MYTOKEN
mia richiesta dal controller angolare:
apiURL = 'http://api.example.com';
$http.get(apiURL + '/roles')
.success(function (roles) { })
.error(function() { });
Yii2 .htaccess: (REST URL del tipo ' http://api.example.com ')
Header always set Access-Control-Allow-Origin: "*"
Header always set Access-Control-Allow-Credentials: true
Header always set Access-Control-Allow-Methods "POST, GET, PUT, DELETE, OPTIONS"
Header always set Access-Control-Allow-Headers "Authorization,X-Requested-With, content-type"
Yii2 mio comportamento:
public function behaviors() {
$behaviors = parent::behaviors();
$behaviors['corsFilter'] = [
'class' => Cors::className(),
'cors' => [
'Origin' => ['*'],
'Access-Control-Expose-Headers' => [
'X-Pagination-Per-Page',
'X-Pagination-Total-Count',
'X-Pagination-Current-Page',
'X-Pagination-Page-Count',
],
],
];
$behaviors['authenticator'] = [
'class' => HttpBearerAuth::className(),
'except' => ['options'],
];
$behaviors['contentNegotiator'] = [
'class' => ContentNegotiator::className(),
'formats' => [
'application/json' => Response::FORMAT_JSON,
],
];
return $behaviors;
}
Problema
Dalla mia richiesta angolare è 'GET' metodo, ma lo farà va metodo 'Opzioni' & tornare errore 401 non autorizzato (CORS). perché l'intestazione Autorizzazione richiesta non viene inviata.
Questo è ora documentato chiaramente qui: http://www.yiiframework.com/doc-2.0/guide-rest-controllers.html # cors - basta seguire questa guida e funzionerà. Riepilogo: assicurati che l'autenticazione venga dopo il comportamento CORS ed escluda OPZIONI dall'autenticazione in qualsiasi momento. – jlapoutre
aggiornato. grazie @jlapoutre –