Sample code for 30+ languages & platforms
PureBasic Requires Chilkat v11.0.0+

Authorize a desktop application to use Gmail

See more GMail REST API Examples

Enable the Gmail API, configure the OAuth consent screen, and create a Desktop app OAuth client. Launch the system browser and receive the authorization code on a loopback listener. The sample requests read-only access with PKCE and offline access. For another operation, select the scope in that example before authorizing. Gmail scopes.

Run in a private, user-only directory. The file contains bearer credentials. In a deployed application use protected credential storage. To reuse an existing grant, copy the older examples’ qa_data/tokens/gmail.json to gmail-token.json in this private directory. The token retains its original scopes. Gmail clients using IMAP, POP, or SMTP with OAuth need the https://mail.google.com/ scope. Use a separate cache for each user and client.

Google documentation

Chilkat PureBasic Downloads

PureBasic
IncludeFile "CkOAuth2.pb"
IncludeFile "CkJsonObject.pb"

Procedure ChilkatExample()

    success.i = 0

    ;  Assumes Chilkat is unlocked. See Global Unlock Sample.

    oauth.i = CkOAuth2::ckCreate()
    If oauth.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkOAuth2::setCkTokenEndpoint(oauth, "https://oauth2.googleapis.com/token")
    CkOAuth2::setCkClientId(oauth, "YOUR_DESKTOP_CLIENT_ID")
    CkOAuth2::setCkClientSecret(oauth, "YOUR_DESKTOP_CLIENT_SECRET")

    CkOAuth2::setCkAuthorizationEndpoint(oauth, "https://accounts.google.com/o/oauth2/v2/auth")
    CkOAuth2::setCkLocalHost(oauth, "127.0.0.1")
    CkOAuth2::setCkListenPort(oauth, 55568)
    CkOAuth2::setCkListenPortRangeEnd(oauth, 55578)
    CkOAuth2::setCkCodeChallenge(oauth, 1)
    CkOAuth2::setCkCodeChallengeMethod(oauth, "S256")
    CkOAuth2::setCkScope(oauth, "https://www.googleapis.com/auth/gmail.readonly")
    success = CkOAuth2::ckAddAuthQueryParam(oauth,"access_type","offline")
    If success <> 1
        Debug "Could not configure offline access."
        CkOAuth2::ckDispose(oauth)
        ProcedureReturn
    EndIf

    ;  This is the interactive setup step. Subsequent refreshes use the saved refresh token.
    success = CkOAuth2::ckAddAuthQueryParam(oauth,"prompt","consent")
    If success <> 1
        Debug "Could not configure consent."
        CkOAuth2::ckDispose(oauth)
        ProcedureReturn
    EndIf

    authUrl.s = CkOAuth2::ckStartAuth(oauth)
    If CkOAuth2::ckLastMethodSuccess(oauth) <> 1
        Debug "Could not start the loopback listener."
        CkOAuth2::ckDispose(oauth)
        ProcedureReturn
    EndIf

    success = CkOAuth2::ckLaunchBrowser(oauth,authUrl)
    If success <> 1
        CkOAuth2::ckCancel(oauth)
        Debug "Could not open the system browser."
        CkOAuth2::ckDispose(oauth)
        ProcedureReturn
    EndIf

    waited.i = 0
    While ((CkOAuth2::ckAuthFlowState(oauth) < 3) AND (waited < 180000))
        CkOAuth2::ckSleepMs(oauth,200)
        waited = waited + 200
    Wend
    If CkOAuth2::ckAuthFlowState(oauth) < 3
        CkOAuth2::ckCancel(oauth)
        Debug "Authorization timed out."
        CkOAuth2::ckDispose(oauth)
        ProcedureReturn
    EndIf

    If CkOAuth2::ckAuthFlowState(oauth) <> 3
        Debug "Authorization did not complete. Flow state: " + Str(CkOAuth2::ckAuthFlowState(oauth))
        CkOAuth2::ckDispose(oauth)
        ProcedureReturn
    EndIf

    token.i = CkJsonObject::ckCreate()
    If token.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkJsonObject::ckLoad(token,CkOAuth2::ckAccessTokenResponse(oauth))
    If success <> 1
        Debug "Could not parse the token response."
        CkOAuth2::ckDispose(oauth)
        CkJsonObject::ckDispose(token)
        ProcedureReturn
    EndIf

    If (CkJsonObject::ckJsonTypeOf(token,"refresh_token") <> 1) OR (CkJsonObject::ckStringOfEquals(token,"refresh_token","",1) = 1)
        Debug "No offline refresh token was issued. The existing cache was preserved."
        CkOAuth2::ckDispose(oauth)
        CkJsonObject::ckDispose(token)
        ProcedureReturn
    EndIf

    success = CkJsonObject::ckWriteFile(token,"gmail-token.json")
    If success <> 1
        Debug "Could not save the token file."
        CkOAuth2::ckDispose(oauth)
        CkJsonObject::ckDispose(token)
        ProcedureReturn
    EndIf

    Debug "Credentials saved in the private working directory."


    CkOAuth2::ckDispose(oauth)
    CkJsonObject::ckDispose(token)


    ProcedureReturn
EndProcedure