| 1 | # Copyright 2013, Google Inc. All Rights Reserved. | ||
| 2 | # | ||
| 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 | ||
| 6 | # | ||
| 7 | # http://www.apache.org/licenses/LICENSE-2.0 | ||
| 8 | # | ||
| 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. | ||
| 14 | |||
| 15 | package Google::Ads::Common::OAuth2ServiceAccountsHandler; | ||
| 16 | |||
| 17 | use strict; | ||
| 18 | use version; | ||
| 19 | use base qw(Google::Ads::Common::OAuth2BaseHandler); | ||
| 20 | |||
| 21 | # The following needs to be on one line because CPAN uses a particularly hacky | ||
| 22 | # eval() to determine module versions. | ||
| 23 | use Google::Ads::Common::Constants; our $VERSION = ${Google::Ads::Common::Constants::VERSION}; | ||
| 24 | |||
| 25 | use Crypt::OpenSSL::RSA; | ||
| 26 | use HTTP::Request; | ||
| 27 | use LWP::UserAgent; | ||
| 28 | use MIME::Base64 qw(encode_base64 decode_base64); | ||
| 29 | use utf8; | ||
| 30 | |||
| 31 | use constant OAUTH2_BASE_URL => "https://accounts.google.com/o/oauth2"; | ||
| 32 | |||
| 33 | # Class::Std-style attributes. Need to be kept in the same line. | ||
| 34 | # These need to go in the same line for older Perl interpreters to understand. | ||
| 35 | my %email_address_of : ATTR(:name<email_address> :default<>); | ||
| 36 | my %delegated_email_address_of : ATTR(:name<delegated_email_address> :default<>); | ||
| 37 | my %pem_file_of : ATTR(:name<pem_file> :default<>); | ||
| 38 | my %__crypt_module_of : ATTR(:name<__crypt_module> :default<>); | ||
| 39 | |||
| 40 | # Constructor | ||
| 41 | sub START { | ||
| 42 | my ($self, $ident) = @_; | ||
| 43 | |||
| 44 | $__crypt_module_of{$ident} ||= "Crypt::OpenSSL::RSA"; | ||
| 45 | } | ||
| 46 | |||
| 47 | sub initialize :CUMULATIVE(BASE FIRST) { | ||
| 48 | my ($self, $api_client, $properties) = @_; | ||
| 49 | my $ident = ident $self; | ||
| 50 | |||
| 51 | $email_address_of{$ident} = $properties->{oAuth2ServiceAccountEmailAddress} || | ||
| 52 | $email_address_of{$ident}; | ||
| 53 | $delegated_email_address_of{$ident} = | ||
| 54 | $properties->{oAuth2ServiceAccountDelegateEmailAddress} || | ||
| 55 | $delegated_email_address_of{$ident}; | ||
| 56 | $pem_file_of{$ident} = $properties->{oAuth2ServiceAccountPEMFile} || | ||
| 57 | $pem_file_of{$ident}; | ||
| 58 | } | ||
| 59 | |||
| 60 | sub _refresh_access_token { | ||
| 61 | my $self = shift; | ||
| 62 | |||
| 63 | my $iat = time; | ||
| 64 | my $exp = $iat + 3600; | ||
| 65 | my $iss = $self->get_email_address(); | ||
| 66 | my $delegated_email_address = $self->get_delegated_email_address(); | ||
| 67 | my $scope = $self->_scope(); | ||
| 68 | |||
| 69 | my $file = $self->__read_certificate_file() || return 0; | ||
| 70 | |||
| 71 | my $header= '{"alg":"RS256","typ":"JWT"}'; | ||
| 72 | my $claims = "{ | ||
| 73 | \"iss\":\"${iss}\", | ||
| 74 | \"prn\":\"${delegated_email_address}\", | ||
| 75 | \"scope\":\"${scope}\", | ||
| 76 | \"aud\":\"" . OAUTH2_BASE_URL . "/token\", | ||
| 77 | \"exp\":${exp}, | ||
| 78 | \"iat\":${iat} | ||
| 79 | }"; | ||
| 80 | |||
| 81 | my $encoded_header = __encode_base64_url($header); | ||
| 82 | my $encoded_claims = __encode_base64_url($claims); | ||
| 83 | my $key = $self->get___crypt_module()->new_private_key($file) || return 0; | ||
| 84 | $key->use_pkcs1_padding(); | ||
| 85 | $key->use_sha256_hash(); | ||
| 86 | |||
| 87 | my $signature = $key->sign("${encoded_header}.${encoded_claims}"); | ||
| 88 | my $encoded_signature = __encode_base64_url($signature); | ||
| 89 | my $assertion = "${encoded_header}.${encoded_claims}.${encoded_signature}"; | ||
| 90 | my $body = "grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer" . | ||
| 91 | "&assertion=" . $assertion; | ||
| 92 | push my @headers, "Content-Type" => "application/x-www-form-urlencoded"; | ||
| 93 | my $request = HTTP::Request->new("POST", OAUTH2_BASE_URL . "/token", | ||
| 94 | \@headers, $body); | ||
| 95 | my $user_agent = $self->get___user_agent(); | ||
| 96 | my $res = $user_agent->request($request); | ||
| 97 | |||
| 98 | if (!$res->is_success()) { | ||
| 99 | warn($res->decoded_content()); | ||
| 100 | return 0; | ||
| 101 | } | ||
| 102 | |||
| 103 | my $content_hash = $self->__parse_auth_response($res->decoded_content()); | ||
| 104 | |||
| 105 | $self->set_access_token($content_hash->{access_token}); | ||
| 106 | $self->set_access_token_expires($iat + $content_hash->{expires_in}); | ||
| 107 | } | ||
| 108 | |||
| 109 | sub __read_certificate_file { | ||
| 110 | my $self = shift; | ||
| 111 | my $file_str; | ||
| 112 | |||
| 113 | $self->get_pem_file() || return 0; | ||
| 114 | open (MYFILE, $self->get_pem_file()) || return 0; | ||
| 115 | while (<MYFILE>) { | ||
| 116 | $file_str .= $_; | ||
| 117 | } | ||
| 118 | close(MYFILE); | ||
| 119 | |||
| 120 | return $file_str; | ||
| 121 | } | ||
| 122 | |||
| 123 | sub __encode_base64_url($) { | ||
| 124 | my ($s) = shift; | ||
| 125 | $s = encode_base64($s); | ||
| 126 | $s =~ tr{+/}{-_}; | ||
| 127 | $s =~ s/=*$//; | ||
| 128 | $s =~ s/\n//g; | ||
| 129 | return $s; | ||
| 130 | } | ||
| 131 | |||
| 132 | sub _scope { | ||
| 133 | my $self = shift; | ||
| 134 | die "Need to be implemented by subclass"; | ||
| 135 | } | ||
| 136 | |||
| 137 | sub _throw_error { | ||
| 138 | my ($self, $err_msg) = @_; | ||
| 139 | |||
| 140 | $self->get_api_client()->get_die_on_faults() ? die($err_msg) : warn($err_msg); | ||
| 141 | } | ||
| 142 | |||
| 143 | 1; | ||
| 144 | |||
| 145 | =pod | ||
| 146 | |||
| 147 | =head1 NAME | ||
| 148 | |||
| 149 | Google::Ads::Common::OAuth2ServiceAccountsHandler | ||
| 150 | |||
| 151 | =head1 DESCRIPTION | ||
| 152 | |||
| 153 | A generic abstract implementation of L<Google::Ads::Common::OAuth2BaseHandler> | ||
| 154 | that supports OAuth2 for Service Accounts semantics. | ||
| 155 | |||
| 156 | It is meant to be specialized and its L<_scope> method be properly implemented. | ||
| 157 | |||
| 158 | =head1 ATTRIBUTES | ||
| 159 | |||
| 160 | Each of these attributes can be set via | ||
| 161 | Google::Ads::Common::OAuth2ServiceAccountsHandler->new(). | ||
| 162 | |||
| 163 | Alternatively, there is a get_ and set_ method associated with each attribute | ||
| 164 | for retrieving or setting them dynamically. | ||
| 165 | |||
| 166 | =head2 api_client | ||
| 167 | |||
| 168 | A reference to the API client used to send requests. | ||
| 169 | |||
| 170 | =head2 client_id | ||
| 171 | |||
| 172 | OAuth2 client id obtained from the Google APIs Console. | ||
| 173 | |||
| 174 | =head2 email_address | ||
| 175 | |||
| 176 | Service account email address as found in the Google API Console. | ||
| 177 | |||
| 178 | =head2 delegated_email_address | ||
| 179 | |||
| 180 | Delegated email address of the accounts that has access to the API. | ||
| 181 | |||
| 182 | =head2 pem_file | ||
| 183 | |||
| 184 | Private key PEM file path. Keep in mind that the Google API Console generates | ||
| 185 | files in PKCS12 format and it should be converted to PEM format with no password | ||
| 186 | for this module to function. | ||
| 187 | |||
| 188 | =head2 access_token | ||
| 189 | |||
| 190 | Stores an OAuth2 access token after the authorization flow is followed or for | ||
| 191 | you to manually set it in case you had it previously stored. | ||
| 192 | If this is manually set this handler will verify its validity before preparing | ||
| 193 | a request. | ||
| 194 | |||
| 195 | =head1 METHODS | ||
| 196 | |||
| 197 | =head2 initialize | ||
| 198 | |||
| 199 | Initializes the handler with properties such as the client_id and | ||
| 200 | client_secret to use for generating authorization requests. | ||
| 201 | |||
| 202 | =head3 Parameters | ||
| 203 | |||
| 204 | =over | ||
| 205 | |||
| 206 | =item * | ||
| 207 | |||
| 208 | A required I<api_client> with a reference to the API client object handling the | ||
| 209 | requests against the API. | ||
| 210 | |||
| 211 | =item * | ||
| 212 | |||
| 213 | A hash reference with the following keys: | ||
| 214 | { | ||
| 215 | # Refer to the documentation of the L<client_id> property. | ||
| 216 | oAuth2ClientId => "client-id", | ||
| 217 | # Refer to the documentation of the L<email_address> property. | ||
| 218 | oAuth2ServiceAccountEmailAddress => "email-address", | ||
| 219 | # Refer to the documentation of the L<delegated_email_address> property. | ||
| 220 | oAuth2ServiceAccountDelegateEmailAddress => "delegated-email-address", | ||
| 221 | # Refer to the documentation of the L<pem_file> property. | ||
| 222 | oAuth2ServiceAccountPEMFile => "pem-file-path", | ||
| 223 | # Refer to the documentation of the L<access_token> property. | ||
| 224 | oAuth2AccessToken => "access-token", | ||
| 225 | } | ||
| 226 | |||
| 227 | =head2 is_auth_enabled | ||
| 228 | |||
| 229 | Refer to L<Google::Ads::Common::AuthHandlerInterface> documentation of this | ||
| 230 | method. | ||
| 231 | |||
| 232 | =head2 prepare_request | ||
| 233 | |||
| 234 | Refer to L<Google::Ads::Common::AuthHandlerInterface> documentation of this | ||
| 235 | method. | ||
| 236 | |||
| 237 | =head1 LICENSE AND COPYRIGHT | ||
| 238 | |||
| 239 | Copyright 2013 Google Inc. | ||
| 240 | |||
| 241 | Licensed under the Apache License, Version 2.0 (the "License"); | ||
| 242 | you may not use this file except in compliance with the License. | ||
| 243 | You may obtain a copy of the License at | ||
| 244 | |||
| 245 | http://www.apache.org/licenses/LICENSE-2.0 | ||
| 246 | |||
| 247 | Unless required by applicable law or agreed to in writing, software | ||
| 248 | distributed under the License is distributed on an "AS IS" BASIS, | ||
| 249 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| 250 | See the License for the specific language governing permissions and | ||
| 251 | limitations under the License. | ||
| 252 | |||
| 253 | =head1 AUTHOR | ||
| 254 | |||
| 255 | David Torres E<lt>david.t at google.comE<gt> | ||
| 256 | |||
| 257 | =head1 REPOSITORY INFORMATION | ||
| 258 | |||
| 259 | $Rev: $ | ||
| 260 | $LastChangedBy: $ | ||
| 261 | $Id: $ | ||
| 262 | |||
| 263 | =cut |