Tôi đã phát triển dịch vụ REST Angular & Yii2 REST. Có vấn đề trong miền chéo. Dưới đây, hãy thêm mã số & Yii2 REST góc cạnh của tôi.Yii2 REST + Tên miền chéo góc CORS
AngularJs: (như 'http://organization1.example.com', 'http://organization2.example.com', ....)
$http.defaults.useXDomain = true;
$http.defaults.withCredentials = true;
$http.defaults.headers.common['Authorization'] = 'Bearer ' + MYTOKEN
Yêu cầu của tôi từ điều khiển góc:
apiURL = 'http://api.example.com';
$http.get(apiURL + '/roles')
.success(function (roles) { })
.error(function() { });
Yii2 .htaccess: (REST URL như ' 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 Hành vi của tôi:
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;
}
Vấn đề
Từ yêu cầu góc của tôi là 'GET' phương pháp, nhưng nó sẽ đi phương pháp 'Options' & trở lại 401 lỗi trái phép (CORS). vì yêu cầu Tiêu đề cấp phép không được gửi.
này bây giờ được ghi chép rõ ràng ở đây: http://www.yiiframework.com/doc-2.0/guide-rest-controllers.html # cors - chỉ cần làm theo hướng dẫn này và nó sẽ hoạt động. Tóm tắt: đảm bảo xác thực đến sau hành vi CORS và loại trừ OPTIONS khỏi xác thực mọi lúc. Đã cập nhật – jlapoutre
. cảm ơn @jlapoutre –