How to parameterise the Access token expiry time while generation

Nandan Hegde 29,911 Reputation points MVP
2020-12-07T11:07:03.037+00:00

Hello All,
I am generating an OAuth token to connect to Azure SQL DB via below powershell code:
$TenantID = ''
$clientId = ''
$resourceAppIdURI = 'https://database.windows.net/'

$tokenResponse = Invoke-RestMethod -Method Post -UseBasicParsing `
    -Uri "https://login.windows.net/$($TenantID)/oauth2/token" `
    -Body @{
        resource=$resourceAppIdURI
        client_id=$clientId
        grant_type='client_credentials'
        client_secret="$(SQLAccessSecret)"
    } -ContentType 'application/x-www-form-urlencoded'

Is there any way I can parameterize the expiry time of that Token to increase it to 5 hrs rather than the default expiry time?

Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
19,918 questions
0 comments No comments
{count} votes

Accepted answer
  1. AmanpreetSingh-MSFT 56,341 Reputation points
    2020-12-07T11:27:04.74+00:00

    @Nandan Hegde · Thank you for reaching out.

    You can use Azure AD Policy to extend the lifetime of Access token (Max 1 day) and assign the policy to the service principal of the application whose client id you are specifying in the token acquisition request. Please refer to below cmdlets for this purpose.

    $policy = New-AzureADPolicy -Definition @('{"TokenLifetimePolicy":{"Version":1,"AccessTokenLifetime":"05:00:00"}}') -DisplayName "AccessTokenPolicy" -IsOrganizationDefault $false -Type "TokenLifetimePolicy"  
      
    Get-AzureADPolicy -Id $policy.Id  
      
    # Get ID of the service principal  
    $sp = Get-AzureADServicePrincipal -Filter "DisplayName eq '<service principal display name>'"  
      
    # Assign policy to a service principal  
    Add-AzureADServicePrincipalPolicy -Id $sp.ObjectId -RefObjectId $policy.Id  
    

    Read more: https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-configurable-token-lifetimes

    -----------------------------------------------------------------------------------------------------------

    Please "Accept the answer" if the information helped you. This will help us and others in the community as well.

    0 comments No comments

0 additional answers

Sort by: Most helpful