Skip to content

Instantly share code, notes, and snippets.

@dmohs
Created August 9, 2016 17:38
Show Gist options
  • Save dmohs/60d8b475ec0d18c96b932d9b7d857044 to your computer and use it in GitHub Desktop.
Save dmohs/60d8b475ec0d18c96b932d9b7d857044 to your computer and use it in GitHub Desktop.
#!/usr/bin/ruby
require 'json'
require 'jwt'
require 'typhoeus'
service_account_data_file_name = ARGV.shift
if not service_account_data_file_name
STDERR.puts "Specify service account file"
exit 1
end
sa_data = JSON.parse(File.read(service_account_data_file_name))
private_key = OpenSSL::PKey::RSA.new sa_data["private_key"]
issue_time = Time.now.strftime("%s").to_i
expiration_time = issue_time + 3600
scopes = [
"email",
"profile",
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/devstorage.full_control",
]
payload = {
:iss => sa_data["client_email"],
:scope => scopes.join(" "),
:aud => "https://www.googleapis.com/oauth2/v4/token",
:exp => expiration_time,
:iat => issue_time
}
assertion = JWT.encode payload, private_key, 'RS256'
response = Typhoeus.post("https://www.googleapis.com/oauth2/v4/token", body: {
grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
assertion: assertion
})
if response.code != 200
STDERR.puts "Token request failed:"
STDERR.puts response.body
exit 1
end
token = JSON.parse(response.body)["access_token"]
puts token
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment