Graph API token expires too quickly

Nadim J 46 Reputation points
2021-11-12T15:25:48.477+00:00

I am using PowerShell to query the audit logs, in this way:

$AccessToken = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
$invokeRest = Invoke-RestMethod -Uri "https://graph.microsoft.com/beta/auditLogs/provisioning" -Method get -Headers @{"Authorization" = "Bearer $($AccessToken)"}
$date = date -f ddMMyyyy_hh_mm
$values = $invokeRest.value
$values | Out-File "c:\temp\$date.txt"

I get the access token from the GraphAPI explorer page. However, this token stops working sometimes after several hours. How do I get one that lasts forever? or at least more than 30 days?

Thanks

Azure Active Directory
Azure Active Directory
An Azure enterprise identity service that provides single sign-on and multi-factor authentication.
12,604 questions
Microsoft Graph Explorer API
{count} votes

Accepted answer
  1. Carl Zhao_MSFT 18,056 Reputation points Microsoft Employee
    2021-11-16T02:25:40.73+00:00

    @Nadim J

    The access token certainly cannot last forever, and its lifetime is about 1 hour. But we can still customize the lifetime of the access token by configuring the token lifetime policy.

     $policy = New-AzureADPolicy -Definition @('{"TokenLifetimePolicy":{"Version":1,"AccessTokenLifetime":"00:15:00"}}') -DisplayName "WebPolicyScenario" -IsOrganizationDefault $false -Type "TokenLifetimePolicy"  
    

    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    No comments

1 additional answer

Sort by: Most helpful
  1. Cristian SPIRIDON 4,301 Reputation points
    2021-11-15T22:33:44.177+00:00

    Hi,

    The duration of the access token is usually 1 hour. After it expire you can request a new one using the refresh token that exist in the powershell session (no reauthentication).
    The refresh token expires after 90 days. More info at:
    https://learn.microsoft.com/en-us/azure/active-directory/develop/refresh-tokens

    Hope this helps!

    No comments