AuthGoogle Chilkat2 Perl Reference Documentation
Chilkat2::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
use Chilkat2;
my $authGoogle = Chilkat2::AuthGoogle->new;
# or set properties (and RaiseError) at creation:
# my $authGoogle = Chilkat2::AuthGoogle->new(VerboseLogging => 1, RaiseError => 1);Creates the object. The optional pairs set writable properties (and RaiseError) in order, as if set one by one; an unknown or read-only name croaks. use Chilkat2; loads every class; the Chilkat2/AuthGoogle.pm file holds only this class's documentation (perldoc Chilkat2::AuthGoogle).
Perl frees the object when its last reference goes (undef $authGoogle, or the variable going out of scope); there is nothing to close. Objects returned by methods are independent and freed the same way. The class may be subclassed (use parent -norequire, 'Chilkat2::AuthGoogle';): an object is a blessed hash reference whose hash is free for the subclass's own fields.
When false (the default), a method that fails returns false (or undef), and the reason is in LastErrorText. When true, it dies with a Chilkat2::Error instead, as DBI does with its RaiseError. Objects returned by a method inherit the value of the object that returned them.
Errors
A Chilkat2::Error stringifies to the failed call's full LastErrorText, and has the methods text, class ('Chilkat2::AuthGoogle'), method (the method name) and object. Methods that look something up and find nothing return undef without dying (each such method says so), methods that answer a question (HasMember, IsUnlocked, ...) return a plain boolean, and property reads and writes never fail for Chilkat reasons.
Misuse always croaks, with your file and line, whatever RaiseError is: a wrong number of arguments, a reference or undef where a string or number is expected, an object of the wrong class, an out-of-range integer, a string containing a NUL character, a wide character in a byte string, or a write to a read-only property.
Strings are Perl character strings in both directions (length, regexes and :encoding layers see characters); binary data (BinData) is a byte string. Unlocking: call Chilkat2::Global->new->UnlockBundle('...') once at startup.
Properties
AccessToken
my $strVal = $authGoogle->AccessToken;
$authGoogle->AccessToken($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
my $strVal = $authGoogle->DebugLogFilePath;
$authGoogle->DebugLogFilePath($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
my $strVal = $authGoogle->EmailAddress;
$authGoogle->EmailAddress($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
my $intVal = $authGoogle->ExpireNumSeconds;
$authGoogle->ExpireNumSeconds($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
my $intVal = $authGoogle->Iat;
$authGoogle->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
my $strVal = $authGoogle->JsonKey;
$authGoogle->JsonKey($strVal);
The JSON key for obtaining an access token. An application must set either the P12 or JSON private key, but not both.
LastErrorHtml
my $strVal = $authGoogle->LastErrorHtml;
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
my $strVal = $authGoogle->LastErrorText;
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
my $strVal = $authGoogle->LastErrorXml;
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
my $boolVal = $authGoogle->LastMethodSuccess;
$authGoogle->LastMethodSuccess($boolVal);
Indicates the success or failure of the most recent method call: 1 means success, 0 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
my $intVal = $authGoogle->NumSecondsRemaining;
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
my $strVal = $authGoogle->Scope;
$authGoogle->Scope($strVal);
A space-delimited list of the permissions that the application requests.
topSubEmailAddress
my $strVal = $authGoogle->SubEmailAddress;
$authGoogle->SubEmailAddress($strVal);
The email address of the user for which the application is requesting delegated access.
topValid
my $boolVal = $authGoogle->Valid;
1 if the AccessToken property contains a valid non-expired access token obtained via the call to ObtainAccessToken.
VerboseLogging
my $boolVal = $authGoogle->VerboseLogging;
$authGoogle->VerboseLogging($boolVal);
If set to 1, then the contents of LastErrorText (or LastErrorXml, or LastErrorHtml) may contain more verbose information. The default value is 0. Verbose logging should only be used for debugging. The potentially large quantity of logged information may adversely affect peformance.
Version
my $strVal = $authGoogle->Version;
Methods
AddClaims
# $success is true or false
my $success = $authGoogle->AddClaims($json);
Adds additional custom claims to the JWT claims set.
Returns true on success, false on failure; LastErrorText says why. With RaiseError on, a failure dies with a Chilkat2::Error instead (it stringifies to the LastErrorText); the object remains usable either way.
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 undef on failure; LastErrorText says why. With RaiseError on, a failure dies with a Chilkat2::Error instead (it stringifies to the LastErrorText); the object remains usable either way. The returned object is new and independent of this one, and inherits its RaiseError.
ObtainAccessToken
# $success is true or false
my $success = $authGoogle->ObtainAccessToken($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, false on failure; LastErrorText says why. With RaiseError on, a failure dies with a Chilkat2::Error instead (it stringifies to the LastErrorText); the object remains usable either way.
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 true on success, false on failure; LastErrorText says why. With RaiseError on, a failure dies with a Chilkat2::Error instead (it stringifies to the LastErrorText); the object remains usable either way.
Events
All Chilkat methods are synchronous: the call returns when the work is done. During a long-running call, Chilkat2::AuthGoogle reports progress to handlers installed with on, which takes Event => CODE pairs (closures, so a handler can use the variables around it):
$authGoogle->on(
PercentDone => sub { my ($pctDone) = @_; print "$pctDone%\n"; return 0 }, # a true return aborts
ProgressInfo => sub { my ($name, $value) = @_; print "$name: $value\n" },
);Installs the handlers given, replacing those installed before for the same events; undef instead of a CODE reference removes one, and $authGoogle->on() with no arguments returns the installed handlers as a list of pairs. The event names are checked: a misspelled one croaks, and nothing is installed.
The AbortCheck handler is called periodically during long operations; PercentDone is called when an operation's completion percentage is known; ProgressInfo delivers named progress values. A true return from the AbortCheck or PercentDone handler aborts the running method, which then fails in the usual way (false or undef, or a Chilkat2::Error under RaiseError).
Handlers run during the method call, on the thread that called it. Inside a handler, other objects may be used, but calling a method of the same object (or its on) croaks. A die in a handler aborts the running method and is re-thrown from the method call; the object remains usable. A handler that uses $authGoogle itself makes a reference cycle: weaken the captured copy (Scalar::Util) or remove the handler when done.
AbortCheck
$authGoogle->on(AbortCheck => sub { ... });
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
my $deadline = time() + 30; # give up after 30 seconds
$authGoogle->on(AbortCheck => sub { return time() > $deadline });PercentDone
$authGoogle->on(PercentDone => sub { ... });
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 1. This will cause the method to terminate and return a failure status or corresponding failure value.
Example
$authGoogle->on(PercentDone => sub {
my ($pctDone) = @_; # 0 to 100
print "Percent done: $pctDone\n";
return 0; # return a true value to abort the method in progress
});ProgressInfo
$authGoogle->on(ProgressInfo => sub { ... });
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
$authGoogle->on(ProgressInfo => sub {
my ($name, $value) = @_;
print "$name: $value\n";
});