Question

I am writing a REST API. In this API I am using a bearer token. This token has a longer expiry time. i.e., several minutes and should be reused until it expires. My REST API may get called concurently from several clients. Whenver, the totken is close to expiry, I need to generate again and store it in a global variable.

Requirement is to delay a function call or fail, when token is being generated. I came across the following topic. Wanted to know whether there is a better method something like mutex in C.

Currency HTTP Requests

Here is my pseduo code:

// lock
if (isset($this->token) == false || ($this->token_expiry_time - time()) < 60) {
    $this->token = $this->generateToken()
}
// unlock
//use token
Was it helpful?

Solution

I suggest you check the Magento API response when you have performed your request. Specifically, you try your API call with an expired token on purpose: the exception message will be useful.

On my local today, I did alter the token to trick my API call to return an error. My error is: {"message":"The consumer isn't authorized to access %resources."..

Once you know the exact message given when an expired token is used, then you can re-authenticate doing like the code below:

$token = $this->getSessionToken();
$response = $this->sendAPICall($token);
$result = $response->getBody();

$result = json_decode($result);
if (strpos($result->message, 'The consumer isn\'t authorized to access') !== false) {
    $token = $this->renewSessionToken();
    
    ... rebuild the API request
    $response = $this->sendAPICall($token);
    $result = $response->getBody();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top