0

I have a PowerShell script that uploads data to a SharePoint site, however, the script needs more than an hour to upload all the data. Is there anyway to increase the tokens life span. Below is the call I use to get the Bearer token

    $TenantId = "T123"
    $ClientId = "C123"
    $Secret = "S123"

    $uri = "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token "

    $body = @{
        grant_type = "client_credentials"
        client_id = $ClientId
        client_secret = $Secret
        scope = "https://graph.microsoft.com/.default"

    }


    #call to get access token
    $resp = Invoke-RestMethod -Method Post -Uri $uri -Body $body -ContentType "application/x-www-form-urlencoded"

mporks
  • 47
  • 1
  • 9
  • `$resp` contains both an access token (which expires after a short while) and a `refresh_token`. To [renew your access token](https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow#refresh-the-access-token), re-submit the same request but with `grant_type = "refresh_token"` and with a `refresh_token = $refreshTokenFromInitialResponse` entry. – Mathias R. Jessen Apr 05 '22 at 11:51
  • When I send the initial request above to get the token, I do not get a refresh_token back in the results, I get { "token_type": "Bearer", "expires_in": 3599, "ext_expires_in": 3599, "access_token": "123123123123" } – mporks Apr 05 '22 at 12:34
  • 1
    Your using the client credential flow so you won't get a refresh token, you will need to renew the token every hour. You can parse the expiry from the token itself or if you want to keep it simple just store the time you acquired the token in a variable and check that before each Invoke-RestMethod request you make if its been more the 50 minutes get a new token. – Glen Scales Apr 05 '22 at 23:42
  • 1
    You may need to change the default token life time with powershell script: https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-configurable-token-lifetimes and you may refer to my [this answer](https://stackoverflow.com/questions/66888660/how-to-manage-session-in-azure-ad-openid-authentication-in-asp-net-core-app/66897950#66897950) – Tiny Wang Apr 06 '22 at 11:31

0 Answers0