Я использую службы angular2 и yii2 restful, но это не работает
Это моя часть angular2
In the userservice
constructor(private http:HttpClientService, private _domaindetails:Domaindetails) { }
profile(val:string="profile"):Observable<User>{
return this.http.get(this.getUserUrl(val))
.map(this.extractData)
}
Это httpclientService
createAuthorizationHeader(headers: Headers) {
let token = JSON.parse(localStorage.getItem("currentUser")).token;
if (token) {
headers.append('Authorization', 'Bearer ' + token);
headers.append('Content-Type', 'application/x-www-form-urlencoded');
headers.append('Content-Type', 'application/json');
}
}
post(url, data) {
let headers = new Headers();
this.createAuthorizationHeader(headers);
return this.http.post(url, data, {
headers: headers
});
}
Это мой бэкэнд в Yii2
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['corsFilter'] = [
'class' => \yii\filters\Cors::className(),
'cors' => [
// restrict access to
'Origin' => ['http://localhost:4200'],
'Access-Control-Request-Method' => ['POST', 'GET','PUT'],
// Allow only POST and PUT methods
'Access-Control-Request-Headers' => ['*'],
// Allow only headers 'X-Wsse'
// 'Access-Control-Allow-Credentials' => true,
// Allow OPTIONS caching
'Access-Control-Max-Age' => 3600,
// Allow the X-Pagination-Current-Page header to be exposed to the browser.
'Access-Control-Expose-Headers' => ['X-Pagination-Current-Page'],
],
];
$auth = $behaviors['authenticator'] = [
'class' => HttpBearerAuth::className(),
'only' => ['can-access','profile'], //access controller
];
$behaviors['authenticator']['except'] = ['options'];
return $behaviors;
}
И действие yii2 не возвращает ошибку несанкционированного доступа
public function actionProfile()
{
$user = Yii::$app->user->identity;
return ['data' => $user];
}
Когда я проверяю Yii::$app->request->headers;
Как видите, токен на предъявителя установлен
Это моя юзермодель
public static function findIdentityByAccessToken($token, $type = null)
{
return static::findOne(['auth_key' => $token]); //auth_key is the value used in bearer token
}
Почему он продолжает возвращать ошибку 401 несанкционированный доступ, и все же, когда я использую то же значение authkey и устанавливаю заголовки носителя авторизации в почтальоне, он работает
После нескольких исследований я обнаружил, что всякий раз, когда angular2 делает запрос, он отправляет запрос параметров, который не работает.