AuthGoogle Zig Reference Documentation
AuthGoogle
Current Version: 11.6.1
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
// Add the package once:
// zig fetch --save https://chilkatdownload.com/11.6.1/chilkat-zig-11.6.1.tar.gz
// and in build.zig:
// const chilkat = b.dependency("chilkat", .{ .target = target, .optimize = optimize });
// exe.root_module.addImport("chilkat", chilkat.module("chilkat"));
const chilkat = @import("chilkat");
// Once per process, before any other Chilkat call:
try chilkat.unlockBundle("Anything for 30-day trial");
const auth_google = try chilkat.AuthGoogle.init();
defer auth_google.deinit();Creates the underlying native Chilkat object. AuthGoogle is a one-pointer struct passed by value; copying it copies the handle (two names for one object). Returns error.OutOfMemory if the library could not allocate the object. Use an object from one thread at a time; it may be handed from one thread to another.
Releases the native object. Call it exactly once per object (usually with defer); the handle is invalid afterwards. Objects returned by methods are owned by the caller too and are released the same way.
Wraps a handle obtained from the C API (chilkat.c.CkAuthGoogle), taking ownership of it. The struct's handle field goes the other way, for anything the Zig API does not cover.
Errors and memory
Methods that can fail return an error union: a method whose only outcome is success or failure returns Error!void; a method producing a string returns (Error || Allocator.Error)![:0]u8; a method producing an object returns Error!T. chilkat.Error is error{ChilkatFailed}; the reason for a failure is in getLastErrorText, and the object remains usable. Properties never fail, and methods that answer a question (hasMember, isUnlocked, ...) return a plain bool.
String arguments are [:0]const u8 (UTF-8; string literals can be passed as is). String results are copies allocated with the allocator argument and owned by the caller, so they stay valid across later calls on the same object.
const text = auth_google.someMethod(allocator, ...) catch |err| {
const why = try auth_google.getLastErrorText(allocator);
defer allocator.free(why);
std.debug.print("{s}\n", .{why});
return err;
};
defer allocator.free(text);
Properties
AccessToken
pub fn getAccessToken(self: AuthGoogle, allocator: Allocator) Allocator.Error![:0]u8
pub fn setAccessToken(self: AuthGoogle, value: [:0]const u8) void
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
pub fn getDebugLogFilePath(self: AuthGoogle, allocator: Allocator) Allocator.Error![:0]u8
pub fn setDebugLogFilePath(self: AuthGoogle, value: [:0]const u8) void
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
pub fn getEmailAddress(self: AuthGoogle, allocator: Allocator) Allocator.Error![:0]u8
pub fn setEmailAddress(self: AuthGoogle, value: [:0]const u8) void
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
pub fn getExpireNumSeconds(self: AuthGoogle) i32
pub fn setExpireNumSeconds(self: AuthGoogle, value: i32) void
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
pub fn getIat(self: AuthGoogle) i32
pub fn setIat(self: AuthGoogle, value: i32) void
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
pub fn getJsonKey(self: AuthGoogle, allocator: Allocator) Allocator.Error![:0]u8
pub fn setJsonKey(self: AuthGoogle, value: [:0]const u8) void
The JSON key for obtaining an access token. An application must set either the P12 or JSON private key, but not both.
LastErrorHtml
pub fn getLastErrorHtml(self: AuthGoogle, allocator: Allocator) Allocator.Error![:0]u8
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
pub fn getLastErrorText(self: AuthGoogle, allocator: Allocator) Allocator.Error![:0]u8
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
pub fn getLastErrorXml(self: AuthGoogle, allocator: Allocator) Allocator.Error![:0]u8
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
pub fn getLastMethodSuccess(self: AuthGoogle) bool
pub fn setLastMethodSuccess(self: AuthGoogle, value: bool) void
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
pub fn getNumSecondsRemaining(self: AuthGoogle) i32
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
pub fn getScope(self: AuthGoogle, allocator: Allocator) Allocator.Error![:0]u8
pub fn setScope(self: AuthGoogle, value: [:0]const u8) void
A space-delimited list of the permissions that the application requests.
topSubEmailAddress
pub fn getSubEmailAddress(self: AuthGoogle, allocator: Allocator) Allocator.Error![:0]u8
pub fn setSubEmailAddress(self: AuthGoogle, value: [:0]const u8) void
The email address of the user for which the application is requesting delegated access.
topValid
pub fn getValid(self: AuthGoogle) bool
true if the AccessToken property contains a valid non-expired access token obtained via the call to ObtainAccessToken.
VerboseLogging
pub fn getVerboseLogging(self: AuthGoogle) bool
pub fn setVerboseLogging(self: AuthGoogle, value: bool) void
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
pub fn getVersion(self: AuthGoogle, allocator: Allocator) Allocator.Error![:0]u8
Methods
AddClaims
Adds additional custom claims to the JWT claims set.
Returns error.ChilkatFailed on failure; getLastErrorText explains why.
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 error.ChilkatFailed on failure; getLastErrorText explains why. The returned object is owned by the caller: release it with deinit.
ObtainAccessToken
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 error.ChilkatFailed on failure; getLastErrorText explains why.
SetP12
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 error.ChilkatFailed on failure; getLastErrorText explains why.
Events
All Chilkat methods are synchronous: the call returns when the work is done. During a call, AuthGoogle raises three events so your program can show progress and offer a way out. Declare any subset of abortCheck, percentDone and progressInfo in a struct of your own and install a pointer to it with setEventHandler:
const Progress = struct {
pub fn percentDone(_: *Progress, pct: i32) bool {
std.debug.print("{d}%\n", .{pct});
return false; // return true to abort the method in progress
}
pub fn progressInfo(_: *Progress, name: [:0]const u8, value: [:0]const u8) void {
std.debug.print("{s}: {s}\n", .{ name, value });
}
};
var progress = Progress{};
auth_google.setEventHandler(&progress); // progress must outlive the installation
defer auth_google.clearEventHandler();
auth_google.setHeartbeatMs(250); // abortCheck 4 times per second during Chilkat callsInstalls handler, a pointer to any struct, as the receiver of this object's events, replacing any handler installed earlier. The dispatch is resolved at compile time: only the methods the struct declares are called, and a struct declaring none of the three is a compile error. The struct must stay alive, at the same address, until clearEventHandler or deinit.
Removes the handler; events are no longer delivered.
AbortCheck fires at regular intervals controlled by the HeartbeatMs property (0, the default, disables it); PercentDone fires when an operation's completion percentage is known; ProgressInfo delivers named progress values. Returning true from abortCheck or percentDone aborts the running method, which then returns error.ChilkatFailed.
Events fire on the thread that called the method, before that method returns. To abort a long operation from another thread, have abortCheck read a std.atomic.Value(bool), or set the object's AbortCurrent property.
AbortCheck
pub fn abortCheck(self: *T) bool
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
const Abort = struct {
stop: std.atomic.Value(bool) = .init(false),
pub fn abortCheck(self: *Abort) bool {
return self.stop.load(.acquire); // another thread may call abort.stop.store(true, .release)
}
};
var abort = Abort{};
auth_google.setHeartbeatMs(250); // call abortCheck 4 times per second
auth_google.setEventHandler(&abort);
defer auth_google.clearEventHandler();PercentDone
pub fn percentDone(self: *T, pct: i32) bool
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
const Progress = struct {
pub fn percentDone(_: *Progress, pct: i32) bool {
// pct ranges from 1 to 100.
std.debug.print("Percent done: {d}\n", .{pct});
return false; // return true to abort the method in progress
}
};
var progress = Progress{};
auth_google.setEventHandler(&progress);
defer auth_google.clearEventHandler();ProgressInfo
pub fn progressInfo(self: *T, name: [:0]const u8, value: [:0]const u8) void
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
const Info = struct {
pub fn progressInfo(_: *Info, name: [:0]const u8, value: [:0]const u8) void {
std.debug.print("{s}: {s}\n", .{ name, value });
}
};
var info = Info{};
auth_google.setEventHandler(&info);
defer auth_google.clearEventHandler();