Skip to content
Advertisement

Laravel app interacting with a 3rd party API to get a token

I have one Laravel app with a GUI where the user logs in based on the data from a MySQL database.

When the user logs in, the server needs to make a request to a specific endpoint of a 3rd party API in order to get a token. This token comes in the response of that request and, since it’s some kind of a session token, it renews from time to time (which implies that this same request which retrieves the token should be called if a particular error is thrown).

In some specific views / routes the associated logic in the controller implies a request to one or more endpoints of that 3rd party API with the previsouly acquired token in the body or in the headers – depending on the endpoint.

I’m mostly concerned if someone gets access to that particular token. If that happens, then they could interact with the 3rd party API and do an unwanted mess. So I’m ok if the pages or operations take a little longer as long as the implemented procedure is very secure (the risk of the previous scenario to happen be extremely low).

What’s the procedure I should aim for? The desired answer would take advantage of Laravel “machineries” and refer where and how this token should be stored.

Advertisement

Answer

In Web Development this scenario usually handles with CSRF token, to ensure the Right user has sending The Request.

from your question i assumed that:

  • your front-end sends request to third-party Api.

  • if your third-party library supports CSRF Protection

My Recommendation is to use an Proxy Design Pattern:

  1. Front-end invoke a route in our back-end.
  2. your back-end route (plays proxy role) requests third-party library with session("third_party_session_token")
  3. Third-party only Responses your back-end.
  4. Back-end return response to front-end.

So in this way, The Third-lib Token Will remain only in Back-end.

Third-party Api-tokens are stored in users session space .

you can use laravel Encryption, if you are worry from session data leakage:

session->put("third_party_api_token",Crypt::encryptString($api_token));

and retrieve it when you want to whitin third-party:

$api_token = Crypt::decryptString(session()->get("third_party_api_token"));

before Encrypting anything you have to generate a key using:

php artisan key:generate

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement