-
-
Save alvarolizama/97cda676356d5356d946e946c14f68fe to your computer and use it in GitHub Desktop.
Authenticate with Google Cloud using service account json key and Elixir
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# https://developers.google.com/identity/protocols/OAuth2ServiceAccount | |
key_json = File.read!("some-service-account-key-file.json") | |
key_map = JOSE.decode(key_json) | |
jwk = JOSE.JWK.from_pem(key_map["private_key"]) | |
jws = %{"alg" => "RS256"} | |
header = %{ | |
"alg" => "RS256", | |
"typ" => "JWT" | |
} | |
iat = :os.system_time(:seconds) | |
exp = iat + 3600 | |
claims = %{ | |
"iss" => key_map["client_email"], | |
"scope" => "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/datastore", | |
"aud" => "https://www.googleapis.com/oauth2/v3/token", | |
"exp" => exp, | |
"iat" => iat | |
} | |
# ok we are finally going to put it altogether and sign it | |
{_, assertion} = JOSE.JWS.sign(jwk, JOSE.encode(claims), header, jws) |> JOSE.JWS.compact | |
# these come from the google auth docs, link at top | |
token_auth_uri = "https://www.googleapis.com/oauth2/v3/token" | |
headers = %{"Content-type" => "application/x-www-form-urlencoded"} | |
form = {:form, [assertion: assertion, grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer"]} | |
#IO.inspect token | |
HTTPoison.start | |
{:ok, response} = HTTPoison.post(token_auth_uri, form, headers) | |
body = JOSE.decode(response.body) | |
access_token = body["access_token"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment