Skip to content

Instantly share code, notes, and snippets.

@mbleigh
Created May 16, 2012 20:48
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 mbleigh/2713830 to your computer and use it in GitHub Desktop.
Save mbleigh/2713830 to your computer and use it in GitHub Desktop.
Google OAuth 2.0 Service Account Authorization
require 'multi_json'
require 'base64'
require 'openssl'
require 'faraday'
now = Time.now.utc.to_i
def encode(hash)
Base64.urlsafe_encode64(MultiJson.dump(hash))
end
header = {
alg: "RS256",
typ: "JWT"
}
claim = {
iss: ARGV[0],
scope: "https://www.google.com/m8/feeds/",
aud: "https://accounts.google.com/o/oauth2/token",
exp: now + 3500,
iat: now.to_i
}
assertion = [encode(header), encode(claim)].join('.')
cert = OpenSSL::PKCS12.new File.open(ARGV[1]){|f| f.read}, 'notasecret'
signature = Base64.urlsafe_encode64 cert.key.sign(OpenSSL::Digest::SHA256.new, assertion)
signed_assertion = [assertion,signature].join('.')
response = Faraday.post("https://accounts.google.com/o/oauth2/token",
grant_type: 'assertion',
assertion_type: 'http://oauth.net/grant_type/jwt/1.0/bearer',
assertion: signed_assertion
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment