1 # Copyright 2010 Google Inc.
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
16 require 'signet/oauth_2/client'
21 # Helper for loading keys from the PKCS12 files downloaded when
22 # setting up service accounts at the APIs Console.
28 # Loads a key from PKCS12 file, assuming a single private key
31 # @param [String] keyfile
32 # Path of the PKCS12 file to load. If not a path to an actual file,
33 # assumes the string is the content of the file itself.
34 # @param [String] passphrase
35 # Passphrase for unlocking the private key
37 # @return [OpenSSL::PKey] The private key for signing assertions.
38 def self.load_key(keyfile, passphrase)
40 if File.exists?(keyfile)
41 content = File.read(keyfile)
45 pkcs12 = OpenSSL::PKCS12.new(content, passphrase)
47 rescue OpenSSL::PKCS12::PKCS12Error
48 raise ArgumentError.new("Invalid keyfile or passphrase")
54 # Generates access tokens using the JWT assertion profile. Requires a
55 # service account & access to the private key.
59 # client = Google::APIClient.new
60 # key = Google::APIClient::PKCS12.load_key('client.p12', 'notasecret')
61 # service_account = Google::APIClient::JWTAsserter(
62 # '123456-abcdef@developer.gserviceaccount.com',
63 # 'https://www.googleapis.com/auth/prediction',
65 # client.authorization = service_account.authorize
68 # @return [String] ID/email of the issuing party
70 # @return [Fixnum] How long, in seconds, the assertion is valid for
72 # @return [Fixnum] Seconds to expand the issued at/expiry window to account for clock skew
74 # @return [String] Scopes to authorize
76 # @return [OpenSSL::PKey] key for signing assertions
80 # Initializes the asserter for a service account.
82 # @param [String] issuer
83 # Name/ID of the client issuing the assertion
84 # @param [String, Array] scope
85 # Scopes to authorize. May be a space delimited string or array of strings
86 # @param [OpenSSL::PKey] key
87 # RSA private key for signing assertions
88 def initialize(issuer, scope, key)
91 self.expiry = 60 # 1 min default
97 # Set the scopes to authorize
99 # @param [String, Array] new_scope
100 # Scopes to authorize. May be a space delimited string or array of strings
101 def scope=(new_scope)
104 @scope = new_scope.join(' ')
110 raise TypeError, "Expected Array or String, got #{new_scope.class}"
115 # Builds & signs the assertion.
117 # @param [String] person
118 # Email address of a user, if requesting a token to act on their behalf
119 # @return [String] Encoded JWT
120 def to_jwt(person=nil)
124 "scope" => self.scope,
125 "aud" => "https://accounts.google.com/o/oauth2/token",
126 "exp" => (now + expiry).to_i,
127 "iat" => (now - skew).to_i
129 assertion['prn'] = person unless person.nil?
130 return JWT.encode(assertion, @key, "RS256")
134 # Request a new access token.
136 # @param [String] person
137 # Email address of a user, if requesting a token to act on their behalf
138 # @param [Hash] options
139 # Pass through to Signet::OAuth2::Client.fetch_access_token
140 # @return [Signet::OAuth2::Client] Access token
142 # @see Signet::OAuth2::Client.fetch_access_token
143 def authorize(person = nil, options={})
144 assertion = self.to_jwt(person)
145 authorization = Signet::OAuth2::Client.new(
146 :token_credential_uri => 'https://accounts.google.com/o/oauth2/token'
148 authorization.grant_type = 'urn:ietf:params:oauth:grant-type:jwt-bearer'
149 authorization.extension_parameters = { :assertion => assertion }
150 authorization.fetch_access_token!(options)