Sample code for 30+ languages & platforms
AutoIt

Automatically Refresh Token for 401 Unauthorized

See more Google Calendar Examples

Demonstrates how to automatically refresh an access token (without user interaction) when the token expires and a 401 Unauthorized response is received.

Chilkat AutoIt Downloads

AutoIt
Local $bSuccess = False

; This example requires the Chilkat API to have been previously unlocked.
; See Global Unlock Sample for sample code.

Local $sTokenFilePath = "qa_data/tokens/googleCalendar.json"

; Get our current access token.
$oJsonToken = ObjCreate("Chilkat.JsonObject")
$bSuccess = $oJsonToken.LoadFile($sTokenFilePath)
If ($oJsonToken.HasMember("access_token") = False) Then
    ConsoleWrite("No access token found." & @CRLF)
    Exit
EndIf

$oHttp = ObjCreate("Chilkat.Http")
$oHttp.AuthToken = $oJsonToken.StringOf("access_token")

Local $sJsonResponse = $oHttp.QuickGetStr("https://www.googleapis.com/calendar/v3/users/me/calendarList")
If ($oHttp.LastMethodSuccess <> True) Then

    If ($oHttp.LastStatus <> 401) Then
        ConsoleWrite($oHttp.LastErrorText & @CRLF)
        ConsoleWrite("----" & @CRLF)
        ConsoleWrite($oHttp.LastResponseBody & @CRLF)
        Exit
    EndIf

    ; The access token must've expired. 
    ; Refresh the access token and then retry the request.
    $oOauth2 = ObjCreate("Chilkat.OAuth2")

    $oOauth2.TokenEndpoint = "https://www.googleapis.com/oauth2/v4/token"

    ; Replace these with actual values.
    $oOauth2.ClientId = "GOOGLE-CLIENT-ID"
    $oOauth2.ClientSecret = "GOOGLE-CLIENT-SECRET"

    ; Get the "refresh_token"
    $oOauth2.RefreshToken = $oJsonToken.StringOf("refresh_token")

    ; Send the HTTP POST to refresh the access token..
    $bSuccess = $oOauth2.RefreshAccessToken()
    If ($bSuccess <> True) Then
        ConsoleWrite($oOauth2.LastErrorText & @CRLF)
        Exit
    EndIf

    ; The response contains a new access token, but we must keep
    ; our existing refresh token for when we need to refresh again in the future.
    $oJsonToken.UpdateString("access_token",$oOauth2.AccessToken)

    ; Save the new JSON access token response to a file.
    $oSbJson = ObjCreate("Chilkat.StringBuilder")
    $oJsonToken.EmitCompact = False
    $oJsonToken.EmitSb($oSbJson)
    $oSbJson.WriteFile($sTokenFilePath,"utf-8",False)

    ConsoleWrite("OAuth2 authorization granted!" & @CRLF)
    ConsoleWrite("New Access Token = " & $oOauth2.AccessToken & @CRLF)

    ; re-try the original request.
    $oHttp.AuthToken = $oOauth2.AccessToken
    $sJsonResponse = $oHttp.QuickGetStr("https://www.googleapis.com/calendar/v3/users/me/calendarList")
    If ($oHttp.LastMethodSuccess <> True) Then
        ConsoleWrite($oHttp.LastErrorText & @CRLF)
        Exit
    EndIf

EndIf

ConsoleWrite($sJsonResponse & @CRLF)
ConsoleWrite("-----------------------------" & @CRLF)