Google + Auth = Goth
A simple library to generate and retrieve OAuth2 tokens for use with Google Cloud Service accounts.
Note: below are instructions for using the upcoming v1.3.0 version. For more information on earlier versions of Goth, see v1.2.0 documentation on hexdocs.pm.
-
Add Goth to your list of dependencies in
mix.exs
:def deps do [{:goth, github: "peburrows/goth"}] 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!() children = [ {Goth, name: MyApp.Goth, credentials: credentials} ] 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" }
Earlier versions of Goth relied on global application environment configuration which is deprecated in favour of a more direct and explicit approach in Goth v1.3+.
You might have code similar to this:
# config/config.exs
config :goth,
json: {:system, "GCP_CREDENTIALS"}
# lib/myapp.ex
defmodule MyApp do
def gcloud_authorization() do
{:ok, token} = Goth.Token.for_scope("https://www.googleapis.com/auth/cloud-platform.read-only")
"#{token.type} #{token.token}"
end
end
Replace it with:
defmodule MyApp.Application do
@moduledoc false
use Application
def start(_type, _args) do
credentials = "GCP_CREDENTIALS" |> System.fetch_env!() |> Jason.decode!()
children = [
{Goth, name: MyApp.Goth, credentials: credentials}
]
Supervisor.start_link(children, strategy: :one_for_one)
end
end
# lib/myapp.ex
defmodule MyApp do
def gcloud_authorization() do
{:ok, token} = Goth.fetch(MyApp.Goth)
"#{token.type} #{token.token}"
end
end
For more information on earlier versions of Goth, see v1.2.0 documentation on hexdocs.pm.