Files

34 lines
1.2 KiB
C++
Raw Permalink Normal View History

// Prints a fresh OAuth2 access token for the configured service account
// (GOOGLE_APPLICATION_CREDENTIALS via env, .env.json.local or .env.json),
// like `gcloud auth print-access-token`. Use only inside command
// substitution so the token never lands in a log:
// export GOOGLE_ACCESS_TOKEN=$(./build/google/sa-token)
#include <iostream>
#include "clients/client.h"
#include "clients/transports/http_transport.h"
#include "google/errors.h"
#include "google/service_account.h"
int main() {
try {
auto auth = molo::google::ServiceAccountAuth::from_env();
if (!auth) {
std::cerr << "sa-token: GOOGLE_APPLICATION_CREDENTIALS is not set\n";
return 2;
}
molo::clients::ClientRequest req = molo::clients::ClientRequest::get("https://example.invalid/");
auth->apply(req);
std::string header = req.headers().get_or("Authorization", "");
if (header.rfind("Bearer ", 0) != 0) {
std::cerr << "sa-token: no bearer produced\n";
return 1;
}
std::cout << header.substr(7) << "\n";
return 0;
} catch (const molo::google::GoogleError& e) {
std::cerr << "sa-token: " << e.status() << ": " << e.message() << "\n";
return 1;
}
}