peburrows / goth

Elixir package for Oauth authentication via Google Cloud APIs
http://hexdocs.pm/goth
MIT License
289 stars 111 forks source link

Feat: retrieve identity token from `metadata` #121

Closed Zat42 closed 2 years ago

Zat42 commented 2 years ago

I do not know if this feature is out of scope since Goth first purpose is to generate and retrieve OAuth2 tokens but I'll give it a shot.

This pull request aims to integrate a feature that will provide users a way to fetch a service account identity token from metadata as it is actually possible for access tokens.

Following Google documentation about VM instance metadata, we can retrieve a JSON Web Token from metadata using the identity entry with an audience parameter. (eg. identity?audience=http://www.example.com)

The idea would be to add an other option called :audience when using metadata as source.

id = MyApp.Goth
audience = "xxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com"
source = {:metadata, audience: audience}
Supervisor.child_spec({Goth, name: id, source: source}, id: id)

If this option is present, we know that we shouldn't query for an access token but for an identity token.

iex> {:ok, token} = Goth.fetch(MyApp.Goth)
iex> token
%Goth.Token{
  scope: "xxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com",
  token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c",
  type: "Bearer",
  expires: 1453356568,
  ...
}
wojtekmach commented 2 years ago

Thank you!