Sample code for 30+ languages & platforms
Swift

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

Swift

func chilkatTest() {
    var success: Bool = false

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

    var tokenFilePath: String? = "qa_data/tokens/googleCalendar.json"

    // Get our current access token.
    let jsonToken = CkoJsonObject()!
    success = jsonToken.loadFile(path: tokenFilePath)
    if jsonToken.hasMember(jsonPath: "access_token") == false {
        print("No access token found.")
        return
    }

    let http = CkoHttp()!
    http.authToken = jsonToken.string(of: "access_token")

    var jsonResponse: String? = http.quickGetStr(url: "https://www.googleapis.com/calendar/v3/users/me/calendarList")
    if http.lastMethodSuccess != true {

        if http.lastStatus.intValue != 401 {
            print("\(http.lastErrorText!)")
            print("----")
            print("\(http.lastResponseBody!)")
            return
        }

        // The access token must've expired. 
        // Refresh the access token and then retry the request.
        let oauth2 = CkoOAuth2()!

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

        // Replace these with actual values.
        oauth2.clientId = "GOOGLE-CLIENT-ID"
        oauth2.clientSecret = "GOOGLE-CLIENT-SECRET"

        // Get the "refresh_token"
        oauth2.refreshToken = jsonToken.string(of: "refresh_token")

        // Send the HTTP POST to refresh the access token..
        success = oauth2.refreshAccessToken()
        if success != true {
            print("\(oauth2.lastErrorText!)")
            return
        }

        // 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.
        jsonToken.updateString(jsonPath: "access_token", value: oauth2.accessToken)

        // Save the new JSON access token response to a file.
        let sbJson = CkoStringBuilder()!
        jsonToken.emitCompact = false
        jsonToken.emitSb(sb: sbJson)
        sbJson.writeFile(path: tokenFilePath, charset: "utf-8", emitBom: false)

        print("OAuth2 authorization granted!")
        print("New Access Token = \(oauth2.accessToken!)")

        // re-try the original request.
        http.authToken = oauth2.accessToken
        jsonResponse = http.quickGetStr(url: "https://www.googleapis.com/calendar/v3/users/me/calendarList")
        if http.lastMethodSuccess != true {
            print("\(http.lastErrorText!)")
            return
        }

    }

    print("\(jsonResponse!)")
    print("-----------------------------")

}