Graph API token expires too quickly

Nadim J 51 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

Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
10,612 questions
Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
19,511 questions
{count} vote

Accepted answer
  1. CarlZhao-MSFT 36,976 Reputation points
    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.


1 additional answer

Sort by: Newest
  1. Cristian SPIRIDON 4,471 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!

    0 comments No comments