Sample code for 30+ languages & platforms
Lianja

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 Lianja Downloads

Lianja
llSuccess = .F.

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

lcTokenFilePath = "qa_data/tokens/googleCalendar.json"

// Get our current access token.
loJsonToken = createobject("CkJsonObject")
llSuccess = loJsonToken.LoadFile(lcTokenFilePath)
if (loJsonToken.HasMember("access_token") = .F.) then
    ? "No access token found."
    release loJsonToken
    return
endif

loHttp = createobject("CkHttp")
loHttp.AuthToken = loJsonToken.StringOf("access_token")

lcJsonResponse = loHttp.QuickGetStr("https://www.googleapis.com/calendar/v3/users/me/calendarList")
if (loHttp.LastMethodSuccess <> .T.) then

    if (loHttp.LastStatus <> 401) then
        ? loHttp.LastErrorText
        ? "----"
        ? loHttp.LastResponseBody
        release loJsonToken
        release loHttp
        return
    endif

    // The access token must've expired. 
    // Refresh the access token and then retry the request.
    loOauth2 = createobject("CkOAuth2")

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

    // Replace these with actual values.
    loOauth2.ClientId = "GOOGLE-CLIENT-ID"
    loOauth2.ClientSecret = "GOOGLE-CLIENT-SECRET"

    // Get the "refresh_token"
    loOauth2.RefreshToken = loJsonToken.StringOf("refresh_token")

    // Send the HTTP POST to refresh the access token..
    llSuccess = loOauth2.RefreshAccessToken()
    if (llSuccess <> .T.) then
        ? loOauth2.LastErrorText
        release loJsonToken
        release loHttp
        release loOauth2
        return
    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.
    loJsonToken.UpdateString("access_token",loOauth2.AccessToken)

    // Save the new JSON access token response to a file.
    loSbJson = createobject("CkStringBuilder")
    loJsonToken.EmitCompact = .F.
    loJsonToken.EmitSb(loSbJson)
    loSbJson.WriteFile(lcTokenFilePath,"utf-8",.F.)

    ? "OAuth2 authorization granted!"
    ? "New Access Token = " + loOauth2.AccessToken

    // re-try the original request.
    loHttp.AuthToken = loOauth2.AccessToken
    lcJsonResponse = loHttp.QuickGetStr("https://www.googleapis.com/calendar/v3/users/me/calendarList")
    if (loHttp.LastMethodSuccess <> .T.) then
        ? loHttp.LastErrorText
        release loJsonToken
        release loHttp
        release loOauth2
        release loSbJson
        return
    endif

endif

? lcJsonResponse
? "-----------------------------"


release loJsonToken
release loHttp
release loOauth2
release loSbJson