I need a little help understanding how often I should be requesting an Access Token when using the Microsoft Graph API. I already have the Enterprise Application created with the proper permissions - everything is working as it should be but I'm not certain I'm correctly using it...
We have a custom Company Directory that loads user profile pictures and their Microsoft Teams presence for each user. Currently I'm requesting the access token on each page load. But is this necessary? Is there a more efficient way to do this such as storing the Access Token in a session? How long does the token last? I'm having a bit of trouble comprehending all this. Any guidance would be greatly appreciated.
I'm requesting the Access Token on each page load by calling a function getAccessToken().
//Get Microsoft Graph API Access Token
function getAccessToken() {
// Set up the request parameters
$clientId = "";
$clientSecret = "";
$tenant_id = "";
$grantType = "client_credentials";
$resource = "https://graph.microsoft.com";
$tokenEndpoint = "https://login.microsoftonline.com/$tenant_id/oauth2/token";
// Build the request body
$requestBody = "client_id=$clientId&client_secret=$clientSecret&grant_type=$grantType&resource=$resource";
// Set up the curl options
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $tokenEndpoint);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestBody);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Execute the request
$response = curl_exec($ch);
curl_close($ch);
// Extract the access token from the response
$responseJson = json_decode($response, true);
$accessToken = $responseJson["access_token"];
return $accessToken;
}
Then depending on the page loaded, I call the getAccessToken() function once at the top of my script and then perform numerous Microsoft Graph API calls for things like profile pictures, user data, and presence information.
Is this the correct way of leveraging the Access Token?
How long does the token last...the response you get when you receive the access token should also include an expiry time. Have a look at the rest of the$responseJsonobject. See also learn.microsoft.com/en-us/graph/auth-v2-service#token-response