0

I have read and attempted to apply the answers to all similar questions. I am missing some key concept, or even attempting a solution in the completely wrong way.

Here is the breakdown of what I'm essentially trying to do:

  1. Bind a singleton in service providers.
public function register()
    {
        $this->app->singleton(RandomApi::class, function () {
            return new RandomApi();
        });
    }
  1. In the RandomApi class itself, it makes a call and retrieves an access token, and sets it such as $this->accessToken.

  2. In a controller, I am type hinting this class such as someMethod(RandomApi $randomApi) in a couple methods. I then check the output of $randomApi->accessToken, and I want it to persist and keep the 1 generated in the binding or 1st instance, however it is continually constructed and generates a new one everytime.

I have tried all the other stackoverflow suggestions on this topic but nothing seems to be working. Am I going about this in completely the wrong way? Is there another better way to retrieve and store access tokens accross a laravel application? Only generating new ones if the single instance in charge of handling the api sees its token expires?

Thank you!

Edit: example of my RandomApi class:

namespace App\Services;

class RandomApi
{

    protected $url = "https://afakeURL.com";
    protected $clientId = 'sdfgsdfgsdfgsdfgsdfg';
    protected $clientSecret = 'sdfgsdfgsdfgsdfgsdfg';
    protected $accessToken;
    protected $client;

    public function __construct()
    {

        $this->client = new \GuzzleHttp\Client([
            'base_uri' => $this->url,
        ]);

        $this->getAccessToken();

    }

    protected function getAccessToken ()
    {
        $response = $this->client->request('POST', "/api/token", [
            'headers' => [
                'Authorization' => 'Basic '.base64_encode($this->clientId.':'.$this->clientSecret)
            ],
            'form_params' => [
                'grant_type' => 'client_credentials'
            ]
        ]);


        $this->accessToken = json_decode($response->getBody()->getContents())->access_token;
    }
Base Desire
  • 485
  • 1
  • 5
  • 15
  • 1
    Could you show us the code for the `RandomApi` class? Additionally are you using the singleton multiple times during a single request? The state does not get preserved across multiple requests. – PtrTon Nov 24 '19 at 13:07
  • @PtrTon I added the code example just swapped out with fake keys/URL. Basically I just am trying to understand what is the best practice way to have essentially one instance for my app authentication, as it will receive back an access token I can then use for all calls. I'm just trying to have my api class persist the generated token, so when I later on make a call using this class, it doesn't make another call for a new token. Right now it is being instantiated everytime so it generates new tokens every time. I thought this would be a good use case for singleton in the service provider but... – Base Desire Nov 24 '19 at 15:43
  • @PtrTon Is there a way I can keep the state of the randomApi class accross request? I'm having a hard time understanding exactly how to cleanly pass it around to other controller methods, I basically want when the app is running, it grabs an access token, and uses that forever until it expires and needs to generate a new one. I just can't seem to figure out the best way to have my randomApi class persist across various requests automagically – Base Desire Nov 24 '19 at 15:46
  • You could store the access token using the [Laravel cache](https://laravel.com/docs/5.8/cache). Depending on the driver this will store the data you pass to it in a file, a database or redis. That should offer a nice way to keep the access token active across multiple requests. – PtrTon Nov 24 '19 at 15:55
  • @PtrTon Thanks, I have google the **** out of this, and cannot find a definitive answer on "Where to store oauth client_credentials access tokens server side". I will try to implement using the cache, then I do not need singletons since the API instance will just be checking the cache... – Base Desire Nov 24 '19 at 16:26

0 Answers0