Goth (Goth v1.3.0-rc.3) View Source
Google + Auth = Goth
A simple library to generate and retrieve OAuth2 tokens for use with Google Cloud Service accounts.
Installation
Note: below are instructions for using Goth v1.3+. For more information on earlier versions of Goth, see v1.2.0 documentation on hexdocs.pm.
Add
:goth
to your list of dependencies inmix.exs
. To use the built-in, Hackney-based HTTP client adapter, add:hackney
too:def deps do [ {:goth, "~> 1.3-rc"}, {:hackney, "~> 1.17"} ] end
Add Goth to your supervision tree:
defmodule MyApp.Application do use Application def start(_type, _args) do credentials = "GOOGLE_APPLICATION_CREDENTIALS_JSON" |> System.fetch_env!() |> Jason.decode!() source = {:service_account, credentials, []} children = [ {Goth, name: MyApp.Goth, source: source} ] Supervisor.start_link(children, strategy: :one_for_one) end end
Fetch the token:
iex> {:ok, token} = Goth.fetch(MyApp.Goth) iex> token %Goth.Token{ expires: 1453356568, token: "ya29.cALlJ4ICWRvMkYB-WsAR-CZnExE459PA7QPqKg5nei9y2T9-iqmbcgxq8XrTATNn_BPim", type: "Bearer", ... }
See Goth.start_link/1
for more information about possible configuration options.
Link to this section Summary
Link to this section Functions
Returns a supervision child spec.
Accepts the same options as start_link/1
.
Fetches the token.
If the token is not in the cache, we immediately request it.
To fetch the token bypassing the cache, see Goth.Token.fetch/1
.
Starts the server.
When the server is started, we attempt to fetch the token and store it in internal cache. If we fail, we'll try up to 3 times with 1000ms cooldown between requests and if we couldn't retrieve it, we crash.
Options
:name
- a unique name to register the server under. It can be any term.:source
- the source to retrieve the token from.See documentation for the
:source
option inGoth.Token.fetch/1
for more information.:retry_after
- Time in milliseconds between retrying requests, defaults to1000
.:refresh_before
- Time in seconds before the token is about to expire that it is tried to be automatically refreshed. Defaults to300
(5 minutes).:http_client
- a{module, opts}
tuple, wheremodule
implements theGoth.HTTPClient
behaviour andopts
is a keywords list to initialize the client with. Defaults to{Goth.HTTPClient.Hackney, []}
.
Examples
Generate a token using a service account credentials file:
iex> credentials = "credentials.json" |> File.read!() |> Jason.decode!()
iex> Goth.start_link(name: MyApp.Goth, source: {:service_account, credentials, []})
iex> Goth.fetch(MyApp.Goth)
{:ok, %Goth.Token{...}}
Retrieve the token using a refresh token:
iex> credentials = "credentials.json" |> File.read!() |> Jason.decode!()
iex> Goth.start_link(name: MyApp.Goth, source: {:refresh_token, credentials, []})
iex> Goth.fetch(MyApp.Goth)
{:ok, %Goth.Token{...}}
Retrieve the token using the Google metadata server:
iex> Goth.start_link(name: MyApp.Goth, source: {:metadata, []})
iex> Goth.fetch(MyApp.Goth)
{:ok, %Goth.Token{...}}