JavaScript
JavaScript
Configure Google Service Account Authentication for REST
See more REST Examples
Demonstrates Rest.SetAuthGoogle, which associates an AuthGoogle provider so Chilkat supplies a Google OAuth 2.0 bearer token on each request. The provider is configured with a service account JSON key and the required OAuth scope.
The file path is relative to the application's current working directory. An absolute path may also be used. Supply the path appropriate to your own environment.
Background. The AuthGoogle provider performs a service-account (server-to-server) OAuth flow. For interactive, browser-based user consent, the OAuth2 provider is used instead.
Note
This example is intended for running within a Chilkat.Js embedded JavaScript engine. All Chilkat JavaScript examples require Chilkat
v11.4.0 or greater.
var success = false;
var rest = new CkRest();
var bTls = true;
var bAutoReconnect = true;
success = rest.Connect("example.com",443,bTls,bAutoReconnect);
if (success == false) {
console.log(rest.LastErrorText);
return;
}
// Configure Google service-account authentication. Load the service account JSON key and set the
// required OAuth scope(s).
var gAuth = new CkAuthGoogle();
var sbJsonKey = new CkStringBuilder();
var bLoaded = sbJsonKey.LoadFile("qa_data/service_account.json");
if (bLoaded !== true) {
console.log("Failed to load the service account JSON key.");
return;
}
var jsonKey = sbJsonKey.GetAsString();
if (sbJsonKey.LastMethodSuccess == false) {
console.log(sbJsonKey.LastErrorText);
return;
}
gAuth.JsonKey = jsonKey;
// A space-delimited list of the requested permissions.
gAuth.Scope = "https://www.googleapis.com/auth/cloud-platform";
// Associate the provider so Chilkat supplies a Google bearer token on each request.
success = rest.SetAuthGoogle(gAuth);
if (success == false) {
console.log(rest.LastErrorText);
return;
}
var responseText = rest.FullRequestNoBody("GET","/storage/v1/b?project=my-project");
if (rest.LastMethodSuccess == false) {
console.log(rest.LastErrorText);
return;
}
console.log(responseText);