You can use the Microsoft Graph PowerShell SDK to create a new token lifetime policy, then assign it to a service principal. When obtaining access tokens for that service principal, you will have the new token lifetime in that token.

Our documentation Create tokenLifetimePolicy – Microsoft Graph v1.0 | Microsoft Learn does not actually give an example of how the JSON should be structured to make this work. This blog post will show you how it is done. I am making a 5 hour Access Token policy for a specific service principal (resource app) that is in my tenant (the resource app). Note, you can do this for any service principal in your tenant, including Microsoft Graph. And then, the token request must be for that application.

This is my $params definition for an Access token. If you set “IsOrganizationDefault” = $true, it will apply to all service principals in your tenant so the recommendation is to leave that as $false and apply it to only service principals you need this policy to be changed for.

$params = @{
    "definition"= @("{'TokenLifetimePolicy':{'Version': 1, 'AccessTokenLifetime': '5:00:00'}}")
    "displayName"= "5hr_AccessTokenPolicy"
    "IsOrganizationDefault" = $false

New-MgPolicyTokenLifetimePolicy -BodyParameter $params 

When I run the New-MgPolicyTokenLifetimePolicy command, it will create it in the tenant. I will need the Id from the output.

You can also get the same output by calling Get-MgPolicyTokenLifetimePolicy and finding it in that output.

Next, I will need to assign that Id to the service principal this token lifetime policy is being applied to. Be sure to use the object id of the service principal for the Parameter -ServicePrincipalId:

$params = @{
    "" = ""

New-MgServicePrincipalTokenLifetimePolicyByRef -ServicePrincipalId e2ef5b0a-7ba9-4c34-9d9a-581dd1e0292b -BodyParameter $params

When making a token request for that service principal, you will now get the extended token lifetime you’re looking for.

Thanks to my team member Will Fiddes for the assistance!

Leave a Comment