# gauth Google API authentication for OCaml. Two flows: **service-account JWT bearer** ([RFC 7523][rfc7523]) for server-to-server access from a JSON key file, and an **interactive local OAuth flow** for CLI tools that spins up a localhost listener and exchanges the authorization code for tokens. Both return a `token` that transparently refreshes credentials near expiry. [rfc7523]: https://www.rfc-editor.org/rfc/rfc7523 ## Installation Install with opam: ```sh $ 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: ```sh $ 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.t` HTTP client and the Eio `clock` are required for refresh: ```ocaml 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][dwd] and impersonate a Workspace user. [dwd]: https://developers.google.com/identity/protocols/oauth2/service-account#delegatingauthority ### 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: ```ocaml let login http ~clock ~net ~sw ~client_id ~client_secret = Gauth.Local_flow.run http ~clock ~net ~sw ~client_id ~client_secret ~scopes:[ "https://www.googleapis.com/auth/documents.readonly" ] () ``` Override `?on_url` to launch a browser automatically instead of printing the URL. ### Persistence Serialize a token to JSON, restore it later — useful for "login once, use many times" CLIs: ```ocaml let save token = Gauth.to_json token let restore http ~clock ~client_id ~client_secret json = Gauth.of_json http ~clock ~client_id ~client_secret json ``` `access` and `try_access` return a current access token, refreshing synchronously if the cached one is near expiry. ## Licence MIT