Skip to content

Instantly share code, notes, and snippets.

@pulkit21
Created April 8, 2016 14:33
Show Gist options
  • Save pulkit21/7300659e33922981ec5887b41691e77d to your computer and use it in GitHub Desktop.
Save pulkit21/7300659e33922981ec5887b41691e77d to your computer and use it in GitHub Desktop.
Validating the request
require 'json/jwt'
require 'jwt'
module GoogleValidation
GOOGLE_CERTS_URI = 'https://www.googleapis.com/oauth2/v3/certs'
REQUIRED_AUDIENCE = ''
REQUIRED_CLIENT_ID = ''
def self.token_validation(token)
google_token = token.split('.')
# From header find the segnature key used
header = JSON.parse(Base64.decode64(google_token[0]))
payload = Base64.decode64(google_token[1])
signature = Base64.decode64(google_token[2])
# Find google key from the list of the certs
public_key = google_certs(header)
# Decode the google token with public key
user_info = decode_google_token(token, public_key)
user_info
end
def self.generate_public_key(key)
jwk = JSON::JWK.new(
kty: :RSA,
e: key["e"],
n: key["n"]
)
jwk.to_key
end
def self.decode_google_token(token, public_key)
begin
decoded_token = JWT.decode(token, public_key, true, { :algorithm => 'RS256' })
if decoded_token[0]["aud"] == REQUIRED_AUDIENCE && decoded_token[0]["azp"] == REQUIRED_CLIENT_ID
return true
else
return false
end
rescue Exception => e
return e.message
end
end
def self.google_certs(header)
uri = URI(GOOGLE_CERTS_URI)
get = Net::HTTP::Get.new uri.request_uri
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
res = http.request(get)
if res.kind_of?(Net::HTTPSuccess)
new_certs = MultiJson.load(res.body).map{|key,value| value}.first.find{|x| x["n"] if x["kid"] == header["kid"]}
# using JWT convert it to public key
public_key = generate_public_key(new_certs)
else
true
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment