Cors :
Код: Выделить всё
'corsFilter' => [
'class' => Cors::class,
'cors' => [
// restrict access to
'Origin' => ['http://192.168.88.29:3000', 'http://localhost:3000', 'http://192.168.88.29:81'],
// TODO заголовки требуют дополнительную проверку
'Access-Control-Allow-Origin' => ['*'],
'Access-Control-Allow-Headers' => [
'Access-Control-Allow-Headers',
'Origin',
'Accept',
'X-Requested-With',
'Content-Type',
'Access-Control-Request-Method',
'Access-Control-Request-Headers',
'Authorization',
'Refresh-Token',
],
// Allow only POST and PUT methods
'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
// Allow only headers 'X-Wsse'
'Access-Control-Request-Headers' => ['X-Wsse'],
// Allow credentials (cookies, authorization headers, etc.) to be exposed to the browser
'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', 'application/json', 'text/plain', '*/*'],
],
],
Код: Выделить всё
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => CompositeAuth::class,
'authMethods' => [
HttpBasicAuth::class,
HttpBearerAuth::class,
HttpHeaderAuth::class,
QueryParamAuth::class
]
];
$behaviors['authenticator']['except'] = ['signup', 'login', 'login-by-pass', 'request-password-reset', 'reset-password', 'oauth'];
return $behaviors;
}
в actionLogin после успешной авторизации по логину и пароли вызываю UserToken::create для записи access_token в бд и вернуть для клиента
Код: Выделить всё
public function actionLogin() {
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
$tokenModel = UserToken::create(
Yii::$app->user->id,
UserToken::TYPE_LOGIN_PASS,
60
);
return [
'variant' => 'success',
'message' => 'Вы успешно авторизованы',
'access_token' => $tokenModel
];
} else {
return [
'variant' => 'danger',
'message' => 'Не удалось авторизоваться',
'errors' => $model->getErrors()
];
}
}
Код: Выделить всё
public static function create($user_id, $type, $duration = null)
{
$model = new self;
$model->setAttributes([
'user_id' => $user_id,
'type' => $type,
// 'token' => (string)random_int(100000, 999999),
'token' => Yii::$app->security->generateRandomKey(self::TOKEN_LENGTH),
'expire_at' => $duration ? time() + $duration : null
]);
if (!$model->save()) {
throw new InvalidCallException;
};
return $model;
}
запрашиваю так:
Код: Выделить всё
export default (values, setMessage, setErrors) => {
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
return axios.post(process.env.apiUrl + '/user/v1/default/login', {LoginForm: values})
.then(function (response) {
const data = response.data;
setMessage({
text:data.mesasge,
variant:data.variant
});
if(data.errors){
setErrors(data.errors);
}
}).catch(function (error) {
console.log(error);
});
};