Check if token is still valid for Microsoft Keyvault with PHP

Viewed 35

To secure our passwords and API keys used on our website we use Microsoft Keyvault on Azure. Every time a user visits our website I make a connection to Keyvault and get the passwords and API keys. This means that every refresh of one of our pages of our website executes the following PHP code. This works perfectly and fast, but I would like to reduce the amount of logins to Microsoft Keyvault.

How can I check if the token is still valid for this user without saving the token in a session.

    // GET TOKEN
$url = "https://login.microsoftonline.com/GUID/oauth2/v2.0/token";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
   "Content-Type: application/x-www-form-urlencoded",
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$data = "grant_type=client_credentials&client_id=GUID&client_secret=CLIENTSECRET&scope=https://vault.azure.net/.default";
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

$response = curl_exec($curl);
$response = json_decode($response, true);
$token = $response['access_token']; 

// LOGIN TO KEYVAULT WITH TOKEN
curl_setopt_array($curl, array(
  CURLOPT_URL => "https://kv-webservice-westus.vault.azure.net/secrets/".$keyvault_secret."?api-version=7.2",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 5,
  CURLOPT_TIMEOUT => 25,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => array(
      'Authorization: Bearer '.$token.''
  ),
));

$response = curl_exec($curl);
curl_close($curl);
$response = json_decode($response, true);
$keyvault_secret = $response['value'];
0 Answers
Related