Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

uniqueginun's avatar

best practice for calling another server to perform a midway authentication

I have some post routes that requires some kind of authentication and the flow is:

  • submit a form which sends a post request
  • in controller I need to submit these data to another API where it requires some Authentication
  • first I check my session for some token, if not I call some API and fetch this token and then send it with the request in the previous step
  • each subsequent request requires this token I need to send it with so I must store it in session or cache

now what is the best way to do this. because I have some scenarios in my mind:

  • make a middleware which check for token in session/cache and if not exists grab them and store them
  • make a dedicated service class which I can resolve from container and then inside this class I perform token request and token store and
0 likes
2 replies
Snapey's avatar
Snapey
Best Answer
Level 122

i would create a service and store the authentication token in cache, in line with its expected validity

This assumes that the token is for the service and not for the specific user that submitted the form

Not a job for middleware

Please or to participate in this conversation.