Answer the question
In order to leave comments, you need to log in
How can you secure your API in a SPA or SSR application?
Hello!
I am developing a web project on VueJs (Nuxt JS SSR). I get all the data from the API (and the API itself is made on Yii2)
Almost 80% of requests to the API go without authorization.
So the question arises - how can you protect the discovery of the API?
I'm new to this...if you have an idea...advise. Is it possible to create some kind of token when the user opens the site and with this token determine where the request comes from in the backend?
Or you can just make a filter by IP address? or website address$_SERVER['HTTP_REFERER']
Answer the question
In order to leave comments, you need to log in
If you want to protect yourself from someone on the front using your API, you can use https://developer.mozilla.org/en/docs/Web/HTTP/CORS.
If you want to protect yourself from someone's backend, then it's much more difficult, almost impossible. Most likely it is to track and ban. Or, at some density of requests, issue a request for a captcha.
You are wasting your time. Your API is just the data you need to render your pages. That is, if it were not for SPA, then you would have all this data immediately on the page.
You just don't have to do anything.
For yii2 there is a regular token mechanism - bearer token
In my project, I created a BaseController inherited from ActiveController and in it a method
public function behaviors()
{
$arBehaviors = parent::behaviors();
$arBehaviors['authenticator'] = [
'class' => HttpBearerAuth::class,
];
$arBehaviors['contentNegotiator'] = [
'class' => ContentNegotiator::class,
'formats' => [
'application/json' => Response::FORMAT_JSON,
],
];
return $arBehaviors;
}
public function actionLogin()
{
$model = new LoginForm();
if ($model->load(Yii::$app->getRequest()->getBodyParams(), '') && $model->login()) {
$oUser = User::findOne(Yii::$app->user->id);
$oUser->generateAuthKey();
$oUser->save();
$userData = $oUser->toArray();
unset($userData['password_hash']);
unset($userData['password_reset_token']);
return ['access_token' => $oUser->getAuthKey(), 'user' => $userData];
}
else {
$model->validate();
return $model;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question