D
D
Dilik Pulatov2019-03-28 12:45:39
RESTful API
Dilik Pulatov, 2019-03-28 12:45:39

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

3 answer(s)
P
pqgg7nwkd4, 2019-03-28
@pqgg7nwkd4

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.

W
WebDev, 2019-03-29
@kirill-93

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.

D
Dmitry Kazarmin, 2019-03-28
@fenix163

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;
  }

In vue, an ajax request is sent to back with a username / password. On the back, something like this action
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 question

Ask a Question

731 491 924 answers to any question