-
Notifications
You must be signed in to change notification settings - Fork 0
Refresh an access token
This sample will be short and sweet, just like the process of refreshing access tokens with New-MSGraphAccessToken
.
If you review the MSGraphPSEssentials README, or any of the other wiki pages here, you likely have read me say, to get a refresh token along with your access token, include the offline_access
scope in the list supplied to the -Scopes
parameter.
Let's use an example from the Get an access token via Device Code flow page:
$DevToken = New-MSGraphAccessToken -ApplicationId <AAD app's ID> -Scopes Sites.Manage.All, offline_access -Endpoint Organizations
If we take a look at $DevToken
, it's going look like this:
$DevToken
token_type : Bearer
scope : Sites.Manage.All profile openid email
expires_in : 3599
ext_expires_in : 3599
access_token : eyJ0eXAiOiJKV1Qi...< lots of characters > ...W0yow
refresh_token : 0.ASwAHZjO8NQxGk...< lots of characters >...6K4dF3A
If we had omitted offline_access
in the -Scopes
parameter, it would have looked exactly the same, except no refresh_token
. Enough said, I'll leave it at that.
I'll pause here to state - you need to know how long your refresh tokens survive in your tenant. The default for Azure AD is 90 days. For Personal Microsoft Accounts, I'm not sure, but it's on Google and Bing. Back to Azure AD, it's possible the default of 90 days is not the case for your tenant, so just know that you need to find that out, or do some trial and error to figure out how often to refresh your tokens to avoid ever having your refresh token expire before you use it.
To refresh the access token and the refresh token, we simply issue this bad boy:
$NewDevToken = New-MSGraphAccessToken -ApplicationId <AAD app's ID> -RefreshToken $DevToken
And that's it. If we now look at $NewDevToken
, we'll see a shiny brand new access token and refresh token:
$NewDevToken
token_type : Bearer
scope : Sites.Manage.All profile openid email
expires_in : 3599
ext_expires_in : 3599
access_token : eyJ0eXAiOiJKV1Qi...< lots of characters > ...FQWt8A
refresh_token : 0.ASwAHZjO8NQxGk...< lots of characters > ...XPNNUQ
At this point, and until the new refresh token expires, we can use the $NewDevToken
with New-MSGraphRequest -AccessToken $NewDevToken
for whatever we need.
⚠ Warning: You want to destroy the previous refresh token ASAP after you have the new one. Also, if the refresh token will be saved somewhere outside of PowerShell, for example, for use in unattended scripts, make sure to store it securely. The refresh token is just as sensitive as a password for an account with the same level of access that was requested/granted when obtaining the original access token. Check out this other sample for one way to securely store the refresh token: Store tokens as PSCredential's in secure XML.