我正在當角2/Yii2應用Yii2 + RESTAPI + CORS +承載方式 - 未授權創建自定義控制器動作
當我調用自定義控制器/動作從郵差與承載頭,一切正常,但是當我打電話它與角度爲2的應用程序(localhost:4200)的頭部相同,我始終得到未經授權的401錯誤。 當我做標準動作像例如從guide喜歡:
GET /users: list all users page by page;
POST /users: create a new user;
一切正常,只有當我創建的自定義操作,比我獲得授權。
這是交叉領域的應用, 角可以用web.example.com, yii2應用是srv.example.com
namespace app\controllers\restapi;
use yii\filters\auth\CompositeAuth;
use yii\filters\auth\HttpBearerAuth;
class SearchOrderController extends \yii\rest\Controller
{
public $modelClass = 'app\models\Order';
public function behaviors()
{
$behaviors = parent::behaviors();
$auth = $behaviors['authenticator'];
unset($behaviors['authenticator']);
$behaviors['corsFilter'] = [
'class' => \yii\filters\Cors::className(),
];
$behaviors['authenticator'] = [
'class' => CompositeAuth::className(),
'authMethods' => [
HttpBearerAuth::className(),
],
];
// avoid authentication on CORS-pre-flight requests (HTTP OPTIONS method)
return $behaviors;
}
public function actionSearch(){
\Yii::$app->response->format=\yii\web\Response::FORMAT_JSON;
return ['index'=>'some text', 'value'=>123];
}
}
而且我的網址經理:
[
'class' => 'yii\rest\UrlRule',
'controller' => 'order',
'pluralize' => false,
'extraPatterns' => [
'GET order/<id:\id+>' => 'order/view',
]
],
[
'class' => 'yii\rest\UrlRule',
'controller' => 'search-order',
'pluralize' => false,
'extraPatterns' => [
'GET search-order/search' => 'search-order/search',
]
你確定GET和POST是失敗的請求嗎?你能否檢查你的瀏覽器的網絡標籤,看看它是不是一個'選項/用戶'失敗的? –
這是選項......因爲我得到的消息是: 選項http://srv.example.com/restapi/search-order/search 401(未授權) 我該怎麼做? – stan