Skip to content

Instantly share code, notes, and snippets.

@soulfly
Last active July 26, 2017 14:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soulfly/a05ac7777739c6fb3475827390ffeef1 to your computer and use it in GitHub Desktop.
Save soulfly/a05ac7777739c6fb3475827390ffeef1 to your computer and use it in GitHub Desktop.
# Get valid JWT public keys and save to cache
#
# Must correspond to one of the public keys listed at
# https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com
#
valid_public_keys = Rails.cache.read(VALID_JWT_PUBLIC_KEYS_RESPONSE_CACHE_KEY)
if valid_public_keys.nil?
uri = URI("https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com")
https = Net::HTTP.new(uri.host, uri.port)
https.use_ssl = true
req = Net::HTTP::Get.new(uri.path)
response = https.request(req)
if response.code != '200'
options['error'] = { 'message' => "Something went wrong: can't obtain valid JWT public keys from Google." }
false
end
valid_public_keys = JSON.parse(response.body)
cc = response["cache-control"] # format example: Cache-Control: public, max-age=24442, must-revalidate, no-transform
max_age = cc[/max-age=(.*?),/m, 1] # get something between 'max-age=' and ','
Rails.cache.write(VALID_JWT_PUBLIC_KEYS_RESPONSE_CACHE_KEY, valid_public_keys, :expires_in => max_age.to_i.seconds)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment