Outlook Calendar: Refresh a Delegated Access Token
See more Outlook Calendar Examples
Refresh the Graph token obtained by the public desktop PKCE example, without a client secret or browser. Use the same client ID and authority. This works after a user has signed in and consented; it is not app-only authentication. A refresh token is not permanent: invalid_grant or an interaction requirement means the user must authorize again.
Form parameters are encoded by Chilkat. HTTP/JSON/token-validation failures leave the old cache untouched. Save a new refresh token when one is returned; retain the previous one if the field is absent. A private backup protects against a replacement-write failure; production code should replace credentials atomically, serialize refreshes per account, and remove obsolete protected backups according to its retention policy. No credentials are printed.
The cache is qa_data/tokens/outlookCalendar.json. Refresh before its acquired-time plus expires_in lifetime has elapsed. Keep each cache associated with its original app and account.
HTTP methods can return false for an HTTP error as well as a connection failure. The code distinguishes those cases and checks the expected status before reading JSON. For 401, refresh the access token or authorize again; for 403, check permissions, mailbox access, and tenant policy. For 429, honor Retry-After before a bounded retry. Do not automatically repeat a write after an uncertain outcome. Keep detailed errors and calendar data private.
Chilkat PowerBuilder Downloads
integer li_rc
long li_Success
oleobject loo_Token
string ls_ClientId
string ls_TokenUrl
oleobject loo_Http
oleobject loo_Req
oleobject loo_Resp
oleobject loo_Result
oleobject loo_Obtained
li_Success = 0
// Assumes Chilkat is unlocked. See Global Unlock Sample.
li_Success = 0
loo_Token = create oleobject
li_rc = loo_Token.ConnectToNewObject("Chilkat.JsonObject")
if li_rc < 0 then
destroy loo_Token
MessageBox("Error","Connecting to COM object failed")
return
end if
loo_Token.Strict = 1
li_Success = loo_Token.LoadFile("qa_data/tokens/outlookCalendar.json")
if li_Success <> 1 then
Write-Debug "Read the private token cache or authorize again."
destroy loo_Token
return
end if
if (loo_Token.JsonTypeOf("refresh_token") <> 1) OR (loo_Token.StringOfEquals("refresh_token","",1) = 1) then
Write-Debug "Expected a nonempty refresh_token in the JSON."
destroy loo_Token
return
end if
ls_ClientId = "YOUR_APPLICATION_CLIENT_ID"
// Use the same app and authority as the original authorization.
ls_TokenUrl = "https://login.microsoftonline.com/common/oauth2/v2.0/token"
loo_Http = create oleobject
li_rc = loo_Http.ConnectToNewObject("Chilkat.Http")
loo_Http.RequireSslCertVerify = 1
loo_Http.FollowRedirects = 0
loo_Http.ConnectTimeout = 20
loo_Http.ReadTimeout = 30
loo_Req = create oleobject
li_rc = loo_Req.ConnectToNewObject("Chilkat.HttpRequest")
loo_Req.HttpVerb = "POST"
loo_Req.ContentType = "application/x-www-form-urlencoded"
loo_Req.AddParam("client_id",ls_ClientId)
loo_Req.AddParam("grant_type","refresh_token")
loo_Req.AddParam("refresh_token",loo_Token.StringOf("refresh_token"))
// Omitting scope retains the original grant instead of requesting additional permissions.
loo_Resp = create oleobject
li_rc = loo_Resp.ConnectToNewObject("Chilkat.HttpResponse")
loo_Result = create oleobject
li_rc = loo_Result.ConnectToNewObject("Chilkat.JsonObject")
loo_Result.Strict = 1
li_Success = loo_Http.HttpReq(ls_TokenUrl,loo_Req,loo_Resp)
// A false result can still include an HTTP error response.
if (li_Success <> 1) AND (loo_Resp.StatusCode = 0) then
Write-Debug "No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying."
destroy loo_Token
destroy loo_Http
destroy loo_Req
destroy loo_Resp
destroy loo_Result
return
end if
if loo_Resp.StatusCode <> 200 then
Write-Debug "Unexpected HTTP status: " + string(loo_Resp.StatusCode)
Write-Debug "Request ID: " + loo_Resp.GetHeaderField("request-id")
if loo_Resp.StatusCode = 429 then
Write-Debug "Retry-After: " + loo_Resp.GetHeaderField("Retry-After")
end if
if loo_Resp.StatusCode = 401 then
Write-Debug "Refresh the Graph access token or authorize again."
end if
destroy loo_Token
destroy loo_Http
destroy loo_Req
destroy loo_Resp
destroy loo_Result
return
end if
li_Success = loo_Result.Load(loo_Resp.BodyStr)
if li_Success <> 1 then
Write-Debug "Expected a well-formed JSON response."
destroy loo_Token
destroy loo_Http
destroy loo_Req
destroy loo_Resp
destroy loo_Result
return
end if
if (loo_Result.JsonTypeOf("access_token") <> 1) OR (loo_Result.StringOfEquals("access_token","",1) = 1) then
Write-Debug "Expected a nonempty access_token in the JSON."
destroy loo_Token
destroy loo_Http
destroy loo_Req
destroy loo_Resp
destroy loo_Result
return
end if
if (loo_Result.JsonTypeOf("expires_in") <> 2) OR (loo_Result.IntOf("expires_in") <= 0) then
Write-Debug "Missing token lifetime; old cache unchanged."
destroy loo_Token
destroy loo_Http
destroy loo_Req
destroy loo_Resp
destroy loo_Result
return
end if
if loo_Result.JsonTypeOf("refresh_token") = -1 then
loo_Result.UpdateString("refresh_token",loo_Token.StringOf("refresh_token"))
else
if (loo_Result.JsonTypeOf("refresh_token") <> 1) OR (loo_Result.StringOfEquals("refresh_token","",1) = 1) then
Write-Debug "Expected a nonempty refresh_token in the JSON."
destroy loo_Token
destroy loo_Http
destroy loo_Req
destroy loo_Resp
destroy loo_Result
return
end if
end if
loo_Obtained = create oleobject
li_rc = loo_Obtained.ConnectToNewObject("Chilkat.CkDateTime")
li_Success = loo_Obtained.SetFromCurrentSystemTime()
if li_Success <> 1 then
Write-Debug "Could not timestamp the refreshed token."
destroy loo_Token
destroy loo_Http
destroy loo_Req
destroy loo_Resp
destroy loo_Result
destroy loo_Obtained
return
end if
loo_Result.UpdateString("obtained_at",loo_Obtained.GetAsTimestamp(0))
// Keep a valid previous cache for recovery if the replacement write fails.
li_Success = loo_Token.WriteFile("qa_data/tokens/outlookCalendar.json.bak")
if li_Success <> 1 then
Write-Debug "Could not back up the old cache; no replacement attempted."
destroy loo_Token
destroy loo_Http
destroy loo_Req
destroy loo_Resp
destroy loo_Result
destroy loo_Obtained
return
end if
li_Success = loo_Result.WriteFile("qa_data/tokens/outlookCalendar.json")
if li_Success <> 1 then
Write-Debug "Could not save the new token; recover the previous cache from the private .bak file."
destroy loo_Token
destroy loo_Http
destroy loo_Req
destroy loo_Resp
destroy loo_Result
destroy loo_Obtained
return
end if
Write-Debug "Refreshed the calendar token cache."
destroy loo_Token
destroy loo_Http
destroy loo_Req
destroy loo_Resp
destroy loo_Result
destroy loo_Obtained