AuthGoogle Lua Reference Documentation
chilkat.AuthGoogle
Current Version: 11.7.0
Markdown version of this page for AI tools (v 11.7.0) · all AI docs
Chilkat.AuthGoogle
Authenticate server-to-server using a Google service account rather than
an interactive browser-based user consent flow.
Load service account credentials from modern JSON private keys or from
legacy P12 private key files.
Specify the OAuth scopes required by the target Google API and add custom
JWT claims when needed.
Use domain-wide delegation by setting a subject email when the service
account is authorized to act on behalf of a Google Workspace user.
Inspect the generated access token, expiration time, remaining lifetime,
and validity state before using or refreshing credentials.
Pass the resulting bearer token to Chilkat HTTP, REST, storage, mail, or
other Google API request workflows.
For an extended overview, see
AuthGoogle Class Overview.
Obtain Google OAuth 2.0 access tokens using a service account.
Chilkat.AuthGoogle obtains OAuth 2.0 access tokens for Google
Cloud Platform APIs and Google Apps APIs using a Google service account. It
supports JSON private keys and P12 private keys, OAuth scopes, optional
delegated user access, custom JWT claims, access-token validity tracking,
token lifetime settings, and integration with Chilkat request classes that
need a Google bearer token.
Service account auth
JSON or P12 keys
Scopes and claims
Delegated user access
Access-token tracking
Chilkat API integration
Scope, optional delegated SubEmailAddress,
and token lifetime, then call ObtainAccessToken. Use
AuthGoogle for service-account OAuth flows; use
Chilkat.OAuth2 when the application needs an interactive
three-legged OAuth flow involving a user's browser consent.
Object Creation
local chilkat = require("chilkat")
local auth_google = chilkat.AuthGoogle.new()Creates the object (chilkat.AuthGoogle() does the same). Lua's garbage collector frees it when it is no longer referenced; auth_google:dispose() frees it at once, and in Lua 5.4 and later local auth_google <close> = chilkat.AuthGoogle.new() frees it when the block ends. Calling a method of a disposed object raises an error.
Errors
A method that fails returns nil followed by the error text, as io.open does: local body, err = auth_google:method(...), where err is the object's last_error_text. Wrap the call in assert() to raise an error with that text instead. Methods that answer a question return true or false, numbers are returned as they are (check last_method_success where the description says a value means failure), and property reads and writes never fail for Chilkat reasons.
Misuse raises a Lua error: a wrong argument type or a missing argument (bad argument #1 to ...), an unknown property name, a write to a read-only property, an out-of-range integer, or an object of the wrong class.
Names are Chilkat's in snake_case: QuickGetStr is quick_get_str, LastErrorText is last_error_text. Properties are fields (auth_google.verbose_logging = true) and methods use the colon (auth_google:method(...)). Strings are UTF-8; binary data is a Lua string of bytes. Indexes are 0-based, as in every Chilkat API. Unlocking: call chilkat.unlock_bundle("...") once at startup.
Properties
AccessToken
local strVal = auth_google.access_token
auth_google.access_token = strVal
The access token to be used in Google API requests. This property is set on a successful call to ObtainAccessToken.
Important: This class is used for authenticating calls to the Google Cloud Platform API and Google Apps API using a service account.. For 3-legged OAuth2, where a browser must be used to interactively get permission from the Google account owner, use the Chilkat OAuth2 class/object.
topDebugLogFilePath
local strVal = auth_google.debug_log_file_path
auth_google.debug_log_file_path = strVal
If set to a file path, this property logs the LastErrorText of each Chilkat method or property call to the specified file. This logging helps identify the context and history of Chilkat calls leading up to any crash or hang, aiding in debugging.
Enabling the VerboseLogging property provides more detailed information. This property is mainly used for debugging rare instances where a Chilkat method call causes a hang or crash, which should generally not happen.
Possible causes of hangs include:
- A timeout property set to 0, indicating an infinite timeout.
- A hang occurring within an event callback in the application code.
- An internal bug in the Chilkat code causing the hang.
EmailAddress
local strVal = auth_google.email_address
auth_google.email_address = strVal
The client email address of the service account. If a JSON key is used, then the client_email should already be specified within the JSON key, and this property is unused. This property must be set if using a P12 key.
ExpireNumSeconds
local intVal = auth_google.expire_num_seconds
auth_google.expire_num_seconds = intVal
The expiration time, in seconds, of the access token to be requested. The maximum value is 1 hour (3600 seconds). The default value is 3600.
topIat
local intVal = auth_google.iat
auth_google.iat = intVal
This property can be set to override the default current date/time value for the iat claim of the JWT. It can be set to a value indicating the number of seconds from 1970-01-01T00:00:00Z UTC.
The default value is 0, which indicates to use the iat value for the current system date/time. Unless explicitly needed, always leave this property at the default value.
topJsonKey
local strVal = auth_google.json_key
auth_google.json_key = strVal
The JSON key for obtaining an access token. An application must set either the P12 or JSON private key, but not both.
LastErrorHtml
local strVal = auth_google.last_error_html
Provides HTML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.
topLastErrorText
local strVal = auth_google.last_error_text
Provides plain text information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.
LastErrorXml
local strVal = auth_google.last_error_xml
Provides XML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.
topLastMethodSuccess
local boolVal = auth_google.last_method_success
auth_google.last_method_success = boolVal
Indicates the success or failure of the most recent method call: true means success, false means failure. This property remains unchanged by property setters or getters. This method is present to address challenges in checking for null or Nothing returns in certain programming languages. Note: This property does not apply to methods that return integer values or to boolean-returning methods where the boolean does not indicate success or failure.
NumSecondsRemaining
local intVal = auth_google.num_seconds_remaining
If the access token is valid, contains the number of seconds remaining until it expires. A value of 0 indicates an invalid or expired access token.
topScope
local strVal = auth_google.scope
auth_google.scope = strVal
A space-delimited list of the permissions that the application requests.
topSubEmailAddress
local strVal = auth_google.sub_email_address
auth_google.sub_email_address = strVal
The email address of the user for which the application is requesting delegated access.
topValid
local boolVal = auth_google.valid
true if the AccessToken property contains a valid non-expired access token obtained via the call to ObtainAccessToken.
VerboseLogging
local boolVal = auth_google.verbose_logging
auth_google.verbose_logging = boolVal
If set to true, then the contents of LastErrorText (or LastErrorXml, or LastErrorHtml) may contain more verbose information. The default value is false. Verbose logging should only be used for debugging. The potentially large quantity of logged information may adversely affect peformance.
Version
local strVal = auth_google.version
Methods
AddClaims
-- ok is true, or nil and err on failure
local ok, err = auth_google:add_claims(json)
Adds additional custom claims to the JWT claims set.
Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.
GetP12
Returns the private key in a PFX (P12) object. This is only possible if the private key was previously set by calling SetP12.
Returns a new object, or nil, err on failure (or when nothing is found). The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead. The returned object is independent of this one.
ObtainAccessToken
-- ok is true, or nil and err on failure
local ok, err = auth_google:obtain_access_token(connection)
Sends the HTTP request to fetch the access token. When this method completes successfully, the access token is available in the AccessToken property. The connection is an existing connection to www.googleapis.com.
Important: Make sure your computer's date/time is accurately set to the current date/time, otherwise you'll get a 400 response status code with this error: Invalid JWT: Token must be a short-lived token (60 minutes) and in a reasonable timeframe. Check your iat and exp values and use a clock with skew to account for clock differences between systems..
Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.
SetP12
-- ok is true, or nil and err on failure
local ok, err = auth_google:set_p12(key)
Sets the P12 private key to be used for obtaining an access token. An application must set either the P12 or JSON private key, but not both.
Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.
Events
All Chilkat methods are synchronous: the call returns when the work is done. During a long-running call, chilkat.AuthGoogle reports progress to the functions given to set_event_handler, in a table keyed by event name (plain functions, not methods: closures carry whatever state they need):
auth_google:set_event_handler({
percent_done = function(pct) print(pct .. "%") end, -- return true to abort
progress_info = function(name, value) print(name, value) end,
})Installs the handlers, replacing any installed before; auth_google:set_event_handler(nil) removes them. The event names are checked when the table is installed: a misspelled one raises an error.
The abort_check handler is called periodically during long operations; percent_done is called when an operation's completion percentage is known; progress_info delivers named progress values. A true return from abort_check or percent_done aborts the running method, which then fails in the usual way (nil, err). An error raised in a handler aborts the method and is raised again from the method call; the object remains usable.
AbortCheck
auth_google:set_event_handler({ abort_check = function() ... end })
Enables a method call to be aborted by triggering the AbortCheck event at intervals defined by the HeartbeatMs property. If HeartbeatMs is set to its default value of 0, no events will occur. For instance, set HeartbeatMs to 200 to trigger 5 AbortCheck events per second.
Example
local deadline = os.time() + 30 -- give up after 30 seconds
auth_google:set_event_handler({ abort_check = function() return os.time() > deadline end })PercentDone
auth_google:set_event_handler({ percent_done = function(pct_done) ... end })
This provides the percentage completion for any method involving network communications or time-consuming processing, assuming the progress can be measured as a percentage. This event is triggered only when it's possible and logical to express the operation's progress as a percentage. The pctDone argument will range from 1 to 100. For methods that finish quickly, the number of PercentDone callbacks may vary, but the final callback will have pctDone equal to 100. For longer operations, callbacks will not exceed one per percentage point (e.g., 1, 2, 3, ..., 98, 99, 100).
The PercentDone callback also acts as an AbortCheck event. For fast methods where PercentDone fires, an AbortCheck event may not trigger since the PercentDone callback already provides an opportunity to abort. For longer operations, where time between PercentDone callbacks is extended, AbortCheck callbacks enable more responsive operation termination.
To abort the operation, set the abort output argument to true. This will cause the method to terminate and return a failure status or corresponding failure value.
Example
auth_google:set_event_handler({
percent_done = function(pct_done) -- 0 to 100
print("Percent done: " .. pct_done)
return false -- return true to abort the method in progress
end,
})ProgressInfo
auth_google:set_event_handler({ progress_info = function(name, value) ... end })
This event callback provides tag name/value pairs that detail what occurs during a method call. To discover existing tag names, create code to handle the event, emit the pairs, and review them. Most tag names are self-explanatory.
Note: Some Chilkat methods don't fire any ProgressInfo events.
Example
auth_google:set_event_handler({
progress_info = function(name, value) print(name .. ": " .. value) end,
})