Chilkat HOME .NET Core C# Android™ AutoIt C C# C++ Chilkat2-Python CkPython Classic ASP DataFlex Delphi ActiveX Delphi DLL Go Java Lianja Mono C# Node.js Objective-C PHP ActiveX PHP Extension Perl PowerBuilder PowerShell PureBasic Ruby SQL Server Swift 2 Swift 3,4,5... Tcl Unicode C Unicode C++ VB.NET VBScript Visual Basic 6.0 Visual FoxPro Xojo Plugin
(AutoIt) Automatically Refresh Token for 401 UnauthorizedDemonstrates how to automatically refresh an access token (without user interaction) when the token expires and a 401 Unauthorized response is received.
; 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") Local $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) |
© 2000-2024 Chilkat Software, Inc. All Rights Reserved.