+ 1# Copyright (C) 2010 Google Inc.
+ 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"""An OAuth 2.0 client.
+ 16
+ 17Tools for interacting with OAuth 2.0 protected resources.
+ 18"""
+ 19
+ 20__author__='jcgregorio@google.com (Joe Gregorio)'
+ 21
+ 22importbase64
+ 23importclientsecrets
+ 24importcopy
+ 25importdatetime
+ 26importhttplib2
+ 27importlogging
+ 28importos
+ 29importsys
+ 30importtime
+ 31importurllib
+ 32importurlparse
+ 33
+ 34fromanyjsonimportsimplejson
+ 35
+ 36HAS_OPENSSL=False
+ 37try:
+ 38fromoauth2client.cryptimportSigner
+ 39fromoauth2client.cryptimportmake_signed_jwt
+ 40fromoauth2client.cryptimportverify_signed_jwt_with_certs
+ 41HAS_OPENSSL=True
+ 42exceptImportError:
+ 43pass
+ 44
+ 45try:
+ 46fromurlparseimportparse_qsl
+ 47exceptImportError:
+ 48fromcgiimportparse_qsl
+ 49
+ 50logger=logging.getLogger(__name__)
+ 51
+ 52# Expiry is stored in RFC3339 UTC format
+ 53EXPIRY_FORMAT='%Y-%m-%dT%H:%M:%SZ'
+ 54
+ 55# Which certs to use to validate id_tokens received.
+ 56ID_TOKEN_VERIFICATON_CERTS='https://www.googleapis.com/oauth2/v1/certs'
+ 57
+ 58# Constant to use for the out of band OAuth 2.0 flow.
+ 59OOB_CALLBACK_URN='urn:ietf:wg:oauth:2.0:oob'
+
112"""Base class for all Credentials objects.
+ 113
+ 114 Subclasses must define an authorize() method that applies the credentials to
+ 115 an HTTP transport.
+ 116
+ 117 Subclasses must also specify a classmethod named 'from_json' that takes a JSON
+ 118 string as input and returns an instaniated Credentials object.
+ 119 """
+ 120
+ 121NON_SERIALIZED_MEMBERS=['store']
+ 122
+
124"""Take an httplib2.Http instance (or equivalent) and
+ 125 authorizes it for the set of credentials, usually by
+ 126 replacing http.request() with a method that adds in
+ 127 the appropriate headers and then delegates to the original
+ 128 Http.request() method.
+ 129 """
+ 130_abstract()
+
133"""Forces a refresh of the access_token.
+ 134
+ 135 Args:
+ 136 http: httplib2.Http, an http object to be used to make the refresh
+ 137 request.
+ 138 """
+ 139_abstract()
+
142"""Add the authorization to the headers.
+ 143
+ 144 Args:
+ 145 headers: dict, the headers to add the Authorization header to.
+ 146 """
+ 147_abstract()
+
150"""Utility function for creating a JSON representation of an instance of Credentials.
+ 151
+ 152 Args:
+ 153 strip: array, An array of names of members to not include in the JSON.
+ 154
+ 155 Returns:
+ 156 string, a JSON representation of this instance, suitable to pass to
+ 157 from_json().
+ 158 """
+ 159t=type(self)
+ 160d=copy.copy(self.__dict__)
+ 161formemberinstrip:
+ 162ifmemberind:
+ 163deld[member]
+ 164if'token_expiry'indandisinstance(d['token_expiry'],datetime.datetime):
+ 165d['token_expiry']=d['token_expiry'].strftime(EXPIRY_FORMAT)
+ 166# Add in information we will need later to reconsistitue this instance.
+ 167d['_class']=t.__name__
+ 168d['_module']=t.__module__
+ 169returnsimplejson.dumps(d)
+
172"""Creating a JSON representation of an instance of Credentials.
+ 173
+ 174 Returns:
+ 175 string, a JSON representation of this instance, suitable to pass to
+ 176 from_json().
+ 177 """
+ 178returnself._to_json(Credentials.NON_SERIALIZED_MEMBERS)
+
182"""Utility class method to instantiate a Credentials subclass from a JSON
+ 183 representation produced by to_json().
+ 184
+ 185 Args:
+ 186 s: string, JSON from to_json().
+ 187
+ 188 Returns:
+ 189 An instance of the subclass of Credentials that was serialized with
+ 190 to_json().
+ 191 """
+ 192data=simplejson.loads(s)
+ 193# Find and call the right classmethod from_json() to restore the object.
+ 194module=data['_module']
+ 195try:
+ 196m=__import__(module)
+ 197exceptImportError:
+ 198# In case there's an object from the old package structure, update it
+ 199module=module.replace('.apiclient','')
+ 200m=__import__(module)
+ 201
+ 202m=__import__(module,fromlist=module.split('.')[:-1])
+ 203kls=getattr(m,data['_class'])
+ 204from_json=getattr(kls,'from_json')
+ 205returnfrom_json(s)
+
209"""Instantiate a Credentials object from a JSON description of it.
+ 210
+ 211 The JSON should have been produced by calling .to_json() on the object.
+ 212
+ 213 Args:
+ 214 data: dict, A deserialized JSON object.
+ 215
+ 216 Returns:
+ 217 An instance of a Credentials subclass.
+ 218 """
+ 219returnCredentials()
+
228"""Base class for all Storage objects.
+ 229
+ 230 Store and retrieve a single credential. This class supports locking
+ 231 such that multiple processes and threads can operate on a single
+ 232 store.
+ 233 """
+ 234
+
251"""Retrieve credential.
+ 252
+ 253 The Storage lock must be held when this is called.
+ 254
+ 255 Returns:
+ 256 oauth2client.client.Credentials
+ 257 """
+ 258_abstract()
+
261"""Write a credential.
+ 262
+ 263 The Storage lock must be held when this is called.
+ 264
+ 265 Args:
+ 266 credentials: Credentials, the credentials to store.
+ 267 """
+ 268_abstract()
+
292"""Write a credential.
+ 293
+ 294 The Storage lock must be held when this is called.
+ 295
+ 296 Args:
+ 297 credentials: Credentials, the credentials to store.
+ 298 """
+ 299self.acquire_lock()
+ 300try:
+ 301self.locked_put(credentials)
+ 302finally:
+ 303self.release_lock()
+
306"""Delete credential.
+ 307
+ 308 Frees any resources associated with storing the credential.
+ 309 The Storage lock must *not* be held when this is called.
+ 310
+ 311 Returns:
+ 312 None
+ 313 """
+ 314self.acquire_lock()
+ 315try:
+ 316returnself.locked_delete()
+ 317finally:
+ 318self.release_lock()
+
322"""Credentials object for OAuth 2.0.
+ 323
+ 324 Credentials can be applied to an httplib2.Http object using the authorize()
+ 325 method, which then adds the OAuth 2.0 access token to each request.
+ 326
+ 327 OAuth2Credentials objects may be safely pickled and unpickled.
+ 328 """
+ 329
+
332"""Create an instance of OAuth2Credentials.
+ 333
+ 334 This constructor is not usually called by the user, instead
+ 335 OAuth2Credentials objects are instantiated by the OAuth2WebServerFlow.
+ 336
+ 337 Args:
+ 338 access_token: string, access token.
+ 339 client_id: string, client identifier.
+ 340 client_secret: string, client secret.
+ 341 refresh_token: string, refresh token.
+ 342 token_expiry: datetime, when the access_token expires.
+ 343 token_uri: string, URI of token endpoint.
+ 344 user_agent: string, The HTTP User-Agent to provide for this application.
+ 345 id_token: object, The identity of the resource owner.
+ 346
+ 347 Notes:
+ 348 store: callable, A callable that when passed a Credential
+ 349 will store the credential back to where it came from.
+ 350 This is needed to store the latest access_token if it
+ 351 has expired and been refreshed.
+ 352 """
+ 353self.access_token=access_token
+ 354self.client_id=client_id
+ 355self.client_secret=client_secret
+ 356self.refresh_token=refresh_token
+ 357self.store=None
+ 358self.token_expiry=token_expiry
+ 359self.token_uri=token_uri
+ 360self.user_agent=user_agent
+ 361self.id_token=id_token
+ 362
+ 363# True if the credentials have been revoked or expired and can't be
+ 364# refreshed.
+ 365self.invalid=False
+
368"""Authorize an httplib2.Http instance with these credentials.
+ 369
+ 370 The modified http.request method will add authentication headers to each
+ 371 request and will refresh access_tokens when a 401 is received on a
+ 372 request. In addition the http.request method has a credentials property,
+ 373 http.request.credentials, which is the Credentials object that authorized
+ 374 it.
+ 375
+ 376 Args:
+ 377 http: An instance of httplib2.Http
+ 378 or something that acts like it.
+ 379
+ 380 Returns:
+ 381 A modified instance of http that was passed in.
+ 382
+ 383 Example:
+ 384
+ 385 h = httplib2.Http()
+ 386 h = credentials.authorize(h)
+ 387
+ 388 You can't create a new OAuth subclass of httplib2.Authenication
+ 389 because it never gets passed the absolute URI, which is needed for
+ 390 signing. So instead we have to overload 'request' with a closure
+ 391 that adds in the Authorization header and then calls the original
+ 392 version of 'request()'.
+ 393 """
+ 394request_orig=http.request
+ 395
+ 396# The closure that will replace 'httplib2.Http.request'.
+ 397defnew_request(uri,method='GET',body=None,headers=None,
+ 398redirections=httplib2.DEFAULT_MAX_REDIRECTS,
+ 399connection_type=None):
+ 400ifnotself.access_token:
+ 401logger.info('Attempting refresh to obtain initial access_token')
+ 402self._refresh(request_orig)
+ 403
+ 404# Modify the request headers to add the appropriate
+ 405# Authorization header.
+ 406ifheadersisNone:
+ 407headers={}
+ 408self.apply(headers)
+ 409
+ 410ifself.user_agentisnotNone:
+ 411if'user-agent'inheaders:
+ 412headers['user-agent']=self.user_agent+' '+headers['user-agent']
+ 413else:
+ 414headers['user-agent']=self.user_agent
+ 415
+ 416resp,content=request_orig(uri,method,body,headers,
+ 417redirections,connection_type)
+ 418
+ 419ifresp.status==401:
+ 420logger.info('Refreshing due to a 401')
+ 421self._refresh(request_orig)
+ 422self.apply(headers)
+ 423returnrequest_orig(uri,method,body,headers,
+ 424redirections,connection_type)
+ 425else:
+ 426return(resp,content)
+
427
+ 428# Replace the request method with our own closure.
+ 429http.request=new_request
+ 430
+ 431# Set credentials as a property of the request method.
+ 432setattr(http.request,'credentials',self)
+ 433
+ 434returnhttp
+
437"""Forces a refresh of the access_token.
+ 438
+ 439 Args:
+ 440 http: httplib2.Http, an http object to be used to make the refresh
+ 441 request.
+ 442 """
+ 443self._refresh(http.request)
+
446"""Add the authorization to the headers.
+ 447
+ 448 Args:
+ 449 headers: dict, the headers to add the Authorization header to.
+ 450 """
+ 451headers['Authorization']='Bearer '+self.access_token
+
507"""Set the Storage for the credential.
+ 508
+ 509 Args:
+ 510 store: Storage, an implementation of Stroage object.
+ 511 This is needed to store the latest access_token if it
+ 512 has expired and been refreshed. This implementation uses
+ 513 locking to check for updates before updating the
+ 514 access_token.
+ 515 """
+ 516self.store=store
+
534"""Generate the body that will be used in the refresh request."""
+ 535body=urllib.urlencode({
+ 536'grant_type':'refresh_token',
+ 537'client_id':self.client_id,
+ 538'client_secret':self.client_secret,
+ 539'refresh_token':self.refresh_token,
+ 540})
+ 541returnbody
+
544"""Generate the headers that will be used in the refresh request."""
+ 545headers={
+ 546'content-type':'application/x-www-form-urlencoded',
+ 547}
+ 548
+ 549ifself.user_agentisnotNone:
+ 550headers['user-agent']=self.user_agent
+ 551
+ 552returnheaders
+
555"""Refreshes the access_token.
+ 556
+ 557 This method first checks by reading the Storage object if available.
+ 558 If a refresh is still needed, it holds the Storage lock until the
+ 559 refresh is completed.
+ 560
+ 561 Args:
+ 562 http_request: callable, a callable that matches the method signature of
+ 563 httplib2.Http.request, used to make the refresh request.
+ 564
+ 565 Raises:
+ 566 AccessTokenRefreshError: When the refresh fails.
+ 567 """
+ 568ifnotself.store:
+ 569self._do_refresh_request(http_request)
+ 570else:
+ 571self.store.acquire_lock()
+ 572try:
+ 573new_cred=self.store.locked_get()
+ 574if(new_credandnotnew_cred.invalidand
+ 575new_cred.access_token!=self.access_token):
+ 576logger.info('Updated access_token read from Storage')
+ 577self._updateFromCredential(new_cred)
+ 578else:
+ 579self._do_refresh_request(http_request)
+ 580finally:
+ 581self.store.release_lock()
+
629"""Credentials object for OAuth 2.0.
+ 630
+ 631 Credentials can be applied to an httplib2.Http object using the
+ 632 authorize() method, which then signs each request from that object
+ 633 with the OAuth 2.0 access token. This set of credentials is for the
+ 634 use case where you have acquired an OAuth 2.0 access_token from
+ 635 another place such as a JavaScript client or another web
+ 636 application, and wish to use it from Python. Because only the
+ 637 access_token is present it can not be refreshed and will in time
+ 638 expire.
+ 639
+ 640 AccessTokenCredentials objects may be safely pickled and unpickled.
+ 641
+ 642 Usage:
+ 643 credentials = AccessTokenCredentials('<an access token>',
+ 644 'my-user-agent/1.0')
+ 645 http = httplib2.Http()
+ 646 http = credentials.authorize(http)
+ 647
+ 648 Exceptions:
+ 649 AccessTokenCredentialsExpired: raised when the access_token expires or is
+ 650 revoked.
+ 651 """
+ 652
+
654"""Create an instance of OAuth2Credentials
+ 655
+ 656 This is one of the few types if Credentials that you should contrust,
+ 657 Credentials objects are usually instantiated by a Flow.
+ 658
+ 659 Args:
+ 660 access_token: string, access token.
+ 661 user_agent: string, The HTTP User-Agent to provide for this application.
+ 662
+ 663 Notes:
+ 664 store: callable, a callable that when passed a Credential
+ 665 will store the credential back to where it came from.
+ 666 """
+ 667super(AccessTokenCredentials,self).__init__(
+ 668access_token,
+ 669None,
+ 670None,
+ 671None,
+ 672None,
+ 673None,
+ 674user_agent)
+
691"""Abstract Credentials object used for OAuth 2.0 assertion grants.
+ 692
+ 693 This credential does not require a flow to instantiate because it
+ 694 represents a two legged flow, and therefore has all of the required
+ 695 information to generate and refresh its own access tokens. It must
+ 696 be subclassed to generate the appropriate assertion string.
+ 697
+ 698 AssertionCredentials objects may be safely pickled and unpickled.
+ 699 """
+ 700
+
704"""Constructor for AssertionFlowCredentials.
+ 705
+ 706 Args:
+ 707 assertion_type: string, assertion type that will be declared to the auth
+ 708 server
+ 709 user_agent: string, The HTTP User-Agent to provide for this application.
+ 710 token_uri: string, URI for token endpoint. For convenience
+ 711 defaults to Google's endpoints but any OAuth 2.0 provider can be used.
+ 712 """
+ 713super(AssertionCredentials,self).__init__(
+ 714None,
+ 715None,
+ 716None,
+ 717None,
+ 718None,
+ 719token_uri,
+ 720user_agent)
+ 721self.assertion_type=assertion_type
+
741# PyOpenSSL is not a prerequisite for oauth2client, so if it is missing then
+ 742# don't create the SignedJwtAssertionCredentials or the verify_id_token()
+ 743# method.
+ 744
+ 745-classSignedJwtAssertionCredentials(AssertionCredentials):
+
746"""Credentials object used for OAuth 2.0 Signed JWT assertion grants.
+ 747
+ 748 This credential does not require a flow to instantiate because it
+ 749 represents a two legged flow, and therefore has all of the required
+ 750 information to generate and refresh its own access tokens.
+ 751 """
+ 752
+ 753MAX_TOKEN_LIFETIME_SECS=3600# 1 hour in seconds
+ 754
+
763"""Constructor for SignedJwtAssertionCredentials.
+ 764
+ 765 Args:
+ 766 service_account_name: string, id for account, usually an email address.
+ 767 private_key: string, private key in P12 format.
+ 768 scope: string or list of strings, scope(s) of the credentials being
+ 769 requested.
+ 770 private_key_password: string, password for private_key.
+ 771 user_agent: string, HTTP User-Agent to provide for this application.
+ 772 token_uri: string, URI for token endpoint. For convenience
+ 773 defaults to Google's endpoints but any OAuth 2.0 provider can be used.
+ 774 kwargs: kwargs, Additional parameters to add to the JWT token, for
+ 775 example prn=joe@xample.org."""
+ 776
+ 777super(SignedJwtAssertionCredentials,self).__init__(
+ 778'http://oauth.net/grant_type/jwt/1.0/bearer',
+ 779user_agent,
+ 780token_uri=token_uri,
+ 781)
+ 782
+ 783iftype(scope)islist:
+ 784scope=' '.join(scope)
+ 785self.scope=scope
+ 786
+ 787self.private_key=private_key
+ 788self.private_key_password=private_key_password
+ 789self.service_account_name=service_account_name
+ 790self.kwargs=kwargs
+
808"""Generate the assertion that will be used in the request."""
+ 809now=long(time.time())
+ 810payload={
+ 811'aud':self.token_uri,
+ 812'scope':self.scope,
+ 813'iat':now,
+ 814'exp':now+SignedJwtAssertionCredentials.MAX_TOKEN_LIFETIME_SECS,
+ 815'iss':self.service_account_name
+ 816}
+ 817payload.update(self.kwargs)
+ 818logger.debug(str(payload))
+ 819
+ 820returnmake_signed_jwt(
+ 821Signer.from_string(self.private_key,self.private_key_password),
+ 822payload)
+
823
+ 824# Only used in verify_id_token(), which is always calling to the same URI
+ 825# for the certs.
+ 826_cached_http=httplib2.Http(MemoryCache())
+
830"""Verifies a signed JWT id_token.
+ 831
+ 832 Args:
+ 833 id_token: string, A Signed JWT.
+ 834 audience: string, The audience 'aud' that the token should be for.
+ 835 http: httplib2.Http, instance to use to make the HTTP request. Callers
+ 836 should supply an instance that has caching enabled.
+ 837 cert_uri: string, URI of the certificates in JSON format to
+ 838 verify the JWT against.
+ 839
+ 840 Returns:
+ 841 The deserialized JSON in the JWT.
+ 842
+ 843 Raises:
+ 844 oauth2client.crypt.AppIdentityError if the JWT fails to verify.
+ 845 """
+ 846ifhttpisNone:
+ 847http=_cached_http
+ 848
+ 849resp,content=http.request(cert_uri)
+ 850
+ 851ifresp.status==200:
+ 852certs=simplejson.loads(content)
+ 853returnverify_signed_jwt_with_certs(id_token,certs,audience)
+ 854else:
+ 855raiseVerifyJwtTokenError('Status code: %d'%resp.status)
+
895"""Constructor for OAuth2WebServerFlow.
+ 896
+ 897 Args:
+ 898 client_id: string, client identifier.
+ 899 client_secret: string client secret.
+ 900 scope: string or list of strings, scope(s) of the credentials being
+ 901 requested.
+ 902 user_agent: string, HTTP User-Agent to provide for this application.
+ 903 auth_uri: string, URI for authorization endpoint. For convenience
+ 904 defaults to Google's endpoints but any OAuth 2.0 provider can be used.
+ 905 token_uri: string, URI for token endpoint. For convenience
+ 906 defaults to Google's endpoints but any OAuth 2.0 provider can be used.
+ 907 **kwargs: dict, The keyword arguments are all optional and required
+ 908 parameters for the OAuth calls.
+ 909 """
+ 910self.client_id=client_id
+ 911self.client_secret=client_secret
+ 912iftype(scope)islist:
+ 913scope=' '.join(scope)
+ 914self.scope=scope
+ 915self.user_agent=user_agent
+ 916self.auth_uri=auth_uri
+ 917self.token_uri=token_uri
+ 918self.params={
+ 919'access_type':'offline',
+ 920}
+ 921self.params.update(kwargs)
+ 922self.redirect_uri=None
+
925"""Returns a URI to redirect to the provider.
+ 926
+ 927 Args:
+ 928 redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob' for
+ 929 a non-web-based application, or a URI that handles the callback from
+ 930 the authorization server.
+ 931
+ 932 If redirect_uri is 'urn:ietf:wg:oauth:2.0:oob' then pass in the
+ 933 generated verification code to step2_exchange,
+ 934 otherwise pass in the query parameters received
+ 935 at the callback uri to step2_exchange.
+ 936 """
+ 937
+ 938self.redirect_uri=redirect_uri
+ 939query={
+ 940'response_type':'code',
+ 941'client_id':self.client_id,
+ 942'redirect_uri':redirect_uri,
+ 943'scope':self.scope,
+ 944}
+ 945query.update(self.params)
+ 946parts=list(urlparse.urlparse(self.auth_uri))
+ 947query.update(dict(parse_qsl(parts[4])))# 4 is the index of the query part
+ 948parts[4]=urllib.urlencode(query)
+ 949returnurlparse.urlunparse(parts)
+
1015"""Create a Flow from a clientsecrets file.
+1016
+1017 Will create the right kind of Flow based on the contents of the clientsecrets
+1018 file or will raise InvalidClientSecretsError for unknown types of Flows.
+1019
+1020 Args:
+1021 filename: string, File name of client secrets.
+1022 scope: string or list of strings, scope(s) to request.
+1023 message: string, A friendly string to display to the user if the
+1024 clientsecrets file is missing or invalid. If message is provided then
+1025 sys.exit will be called in the case of an error. If message in not
+1026 provided then clientsecrets.InvalidClientSecretsError will be raised.
+1027
+1028 Returns:
+1029 A Flow object.
+1030
+1031 Raises:
+1032 UnknownClientSecretsFlowError if the file describes an unknown kind of Flow.
+1033 clientsecrets.InvalidClientSecretsError if the clientsecrets file is
+1034 invalid.
+1035 """
+1036try:
+1037client_type,client_info=clientsecrets.loadfile(filename)
+1038ifclient_typein[clientsecrets.TYPE_WEB,clientsecrets.TYPE_INSTALLED]:
+1039returnOAuth2WebServerFlow(
+1040client_info['client_id'],
+1041client_info['client_secret'],
+1042scope,
+1043None,# user_agent
+1044client_info['auth_uri'],
+1045client_info['token_uri'])
+1046exceptclientsecrets.InvalidClientSecretsError:
+1047ifmessage:
+1048sys.exit(message)
+1049else:
+1050raise
+1051else:
+1052raiseUnknownClientSecretsFlowError(
+1053'This OAuth 2.0 flow is unsupported: "%s"'*client_type)
+