Google API authentication helpers: service accounts and local OAuth
README.md

gauth #

Google API authentication for OCaml.

Every call to a Google API needs a short-lived bearer token, and getting one means either signing a JWT with a service-account key or walking a user through OAuth consent in a browser. gauth does both. The service-account flow implements the JWT bearer grant of RFC 7523 for server-to-server access from a JSON key file. The local OAuth flow is for command-line tools: it listens on 127.0.0.1, sends the user to Google's consent page and exchanges the returned authorisation code for tokens. Both return a token that refreshes itself when it is within 60 seconds of expiry, and Local_store keeps the client and token on disk so a user logs in once.

Installation #

Install with opam:

$ opam install gauth

If opam cannot find the package, it may not yet be released in the public opam-repository. Add the overlay repository, then install it:

$ opam repo add samoht https://tangled.org/gazagnaire.org/opam-overlay.git
$ opam update
$ opam install gauth

Usage #

Service account #

Parse a service-account JSON key and mint an access token for a set of OAuth scopes. The Requests_eio.t HTTP client and the Eio clock are required for refresh:

let fetch_token http ~clock ~key_path =
  match Gauth.Service_account.of_file key_path with
  | Error (`Msg m) -> Error m
  | Ok key ->
      let scopes =
        [ "https://www.googleapis.com/auth/documents.readonly" ] in
      match Gauth.Service_account.token http ~clock ~scopes key with
      | Ok token -> Ok (Gauth.access token)
      | Error (`Msg m) -> Error m

Pass ?subject:"alice@example.com" to Service_account.token to use domain-wide delegation and impersonate a Workspace user.

Interactive local flow #

Local_flow.run binds an ephemeral port on 127.0.0.1, prints a Google consent URL to stderr, and waits up to ?timeout seconds (default 120) for the user to complete the flow:

let login http ~clock ~net ~sw ~id ~secret =
  Gauth.Local_flow.run http ~clock ~net ~sw
    ~id ~secret
    ~scopes:[ "https://www.googleapis.com/auth/documents.readonly" ]
    ()

Override ?on_url to launch a browser automatically instead of printing the URL.

Persistence #

Serialise a token to JSON and restore it later, so that a CLI needs only one login:

let save token = Gauth.json_of_token token

let restore http ~clock ~id ~secret json =
  Gauth.of_json http ~clock ~id ~secret json

access and try_access return a current access token, refreshing synchronously if the cached one is near expiry. access raises Failure when the refresh fails; try_access returns the error.

License #

ISC. See LICENSE.md.