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

1 Answer 1


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();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.