Joe Gregorio | 20a5aa9 | 2011-04-01 17:44:25 -0400 | [diff] [blame] | 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. |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 14 | |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 15 | """An OAuth 2.0 client. |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 16 | |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 17 | Tools for interacting with OAuth 2.0 protected resources. |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 18 | """ |
| 19 | |
| 20 | __author__ = 'jcgregorio@google.com (Joe Gregorio)' |
| 21 | |
Joe Gregorio | 8b4c173 | 2011-12-06 11:28:29 -0500 | [diff] [blame] | 22 | import base64 |
Joe Gregorio | f08a498 | 2011-10-07 13:11:16 -0400 | [diff] [blame] | 23 | import clientsecrets |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 24 | import copy |
| 25 | import datetime |
| 26 | import httplib2 |
| 27 | import logging |
Joe Gregorio | 8b4c173 | 2011-12-06 11:28:29 -0500 | [diff] [blame] | 28 | import os |
Joe Gregorio | f08a498 | 2011-10-07 13:11:16 -0400 | [diff] [blame] | 29 | import sys |
Joe Gregorio | 8b4c173 | 2011-12-06 11:28:29 -0500 | [diff] [blame] | 30 | import time |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 31 | import urllib |
| 32 | import urlparse |
| 33 | |
Joe Gregorio | 549230c | 2012-01-11 10:38:05 -0500 | [diff] [blame] | 34 | from anyjson import simplejson |
Joe Gregorio | 8b4c173 | 2011-12-06 11:28:29 -0500 | [diff] [blame] | 35 | |
| 36 | HAS_OPENSSL = False |
| 37 | try: |
| 38 | from oauth2client.crypt import Signer |
| 39 | from oauth2client.crypt import make_signed_jwt |
| 40 | from oauth2client.crypt import verify_signed_jwt_with_certs |
| 41 | HAS_OPENSSL = True |
| 42 | except ImportError: |
| 43 | pass |
| 44 | |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 45 | try: |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 46 | from urlparse import parse_qsl |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 47 | except ImportError: |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 48 | from cgi import parse_qsl |
| 49 | |
Joe Gregorio | 8b4c173 | 2011-12-06 11:28:29 -0500 | [diff] [blame] | 50 | # Determine if we can write to the file system, and if we can use a local file |
| 51 | # cache behing httplib2. |
| 52 | if hasattr(os, 'tempnam'): |
| 53 | # Put cache file in the director '.cache'. |
| 54 | CACHED_HTTP = httplib2.Http('.cache') |
| 55 | else: |
| 56 | CACHED_HTTP = httplib2.Http() |
| 57 | |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 58 | logger = logging.getLogger(__name__) |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 59 | |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 60 | # Expiry is stored in RFC3339 UTC format |
Joe Gregorio | 8b4c173 | 2011-12-06 11:28:29 -0500 | [diff] [blame] | 61 | EXPIRY_FORMAT = '%Y-%m-%dT%H:%M:%SZ' |
| 62 | |
| 63 | # Which certs to use to validate id_tokens received. |
| 64 | ID_TOKEN_VERIFICATON_CERTS = 'https://www.googleapis.com/oauth2/v1/certs' |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 65 | |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 66 | |
| 67 | class Error(Exception): |
| 68 | """Base error for this module.""" |
| 69 | pass |
| 70 | |
| 71 | |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 72 | class FlowExchangeError(Error): |
Joe Gregorio | ca876e4 | 2011-02-22 19:39:42 -0500 | [diff] [blame] | 73 | """Error trying to exchange an authorization grant for an access token.""" |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 74 | pass |
| 75 | |
| 76 | |
| 77 | class AccessTokenRefreshError(Error): |
Joe Gregorio | ca876e4 | 2011-02-22 19:39:42 -0500 | [diff] [blame] | 78 | """Error trying to refresh an expired access token.""" |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 79 | pass |
| 80 | |
Joe Gregorio | f08a498 | 2011-10-07 13:11:16 -0400 | [diff] [blame] | 81 | class UnknownClientSecretsFlowError(Error): |
| 82 | """The client secrets file called for an unknown type of OAuth 2.0 flow. """ |
| 83 | pass |
| 84 | |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 85 | |
Joe Gregorio | 3b79fa8 | 2011-02-17 11:47:17 -0500 | [diff] [blame] | 86 | class AccessTokenCredentialsError(Error): |
| 87 | """Having only the access_token means no refresh is possible.""" |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 88 | pass |
| 89 | |
| 90 | |
Joe Gregorio | 8b4c173 | 2011-12-06 11:28:29 -0500 | [diff] [blame] | 91 | class VerifyJwtTokenError(Error): |
| 92 | """Could on retrieve certificates for validation.""" |
| 93 | pass |
| 94 | |
| 95 | |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 96 | def _abstract(): |
| 97 | raise NotImplementedError('You need to override this function') |
| 98 | |
| 99 | |
| 100 | class Credentials(object): |
| 101 | """Base class for all Credentials objects. |
| 102 | |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 103 | Subclasses must define an authorize() method that applies the credentials to |
| 104 | an HTTP transport. |
| 105 | |
| 106 | Subclasses must also specify a classmethod named 'from_json' that takes a JSON |
| 107 | string as input and returns an instaniated Crentials object. |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 108 | """ |
| 109 | |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 110 | NON_SERIALIZED_MEMBERS = ['store'] |
| 111 | |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 112 | def authorize(self, http): |
| 113 | """Take an httplib2.Http instance (or equivalent) and |
| 114 | authorizes it for the set of credentials, usually by |
| 115 | replacing http.request() with a method that adds in |
| 116 | the appropriate headers and then delegates to the original |
| 117 | Http.request() method. |
| 118 | """ |
| 119 | _abstract() |
| 120 | |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 121 | def _to_json(self, strip): |
| 122 | """Utility function for creating a JSON representation of an instance of Credentials. |
| 123 | |
| 124 | Args: |
| 125 | strip: array, An array of names of members to not include in the JSON. |
| 126 | |
| 127 | Returns: |
| 128 | string, a JSON representation of this instance, suitable to pass to |
| 129 | from_json(). |
| 130 | """ |
| 131 | t = type(self) |
| 132 | d = copy.copy(self.__dict__) |
| 133 | for member in strip: |
| 134 | del d[member] |
| 135 | if 'token_expiry' in d and isinstance(d['token_expiry'], datetime.datetime): |
| 136 | d['token_expiry'] = d['token_expiry'].strftime(EXPIRY_FORMAT) |
| 137 | # Add in information we will need later to reconsistitue this instance. |
| 138 | d['_class'] = t.__name__ |
| 139 | d['_module'] = t.__module__ |
| 140 | return simplejson.dumps(d) |
| 141 | |
| 142 | def to_json(self): |
| 143 | """Creating a JSON representation of an instance of Credentials. |
| 144 | |
| 145 | Returns: |
| 146 | string, a JSON representation of this instance, suitable to pass to |
| 147 | from_json(). |
| 148 | """ |
| 149 | return self._to_json(Credentials.NON_SERIALIZED_MEMBERS) |
| 150 | |
| 151 | @classmethod |
| 152 | def new_from_json(cls, s): |
| 153 | """Utility class method to instantiate a Credentials subclass from a JSON |
| 154 | representation produced by to_json(). |
| 155 | |
| 156 | Args: |
| 157 | s: string, JSON from to_json(). |
| 158 | |
| 159 | Returns: |
| 160 | An instance of the subclass of Credentials that was serialized with |
| 161 | to_json(). |
| 162 | """ |
| 163 | data = simplejson.loads(s) |
| 164 | # Find and call the right classmethod from_json() to restore the object. |
| 165 | module = data['_module'] |
Joe Gregorio | e9b40f1 | 2011-10-13 10:03:28 -0400 | [diff] [blame] | 166 | m = __import__(module, fromlist=module.split('.')[:-1]) |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 167 | kls = getattr(m, data['_class']) |
| 168 | from_json = getattr(kls, 'from_json') |
| 169 | return from_json(s) |
| 170 | |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 171 | |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 172 | class Flow(object): |
| 173 | """Base class for all Flow objects.""" |
| 174 | pass |
| 175 | |
| 176 | |
Joe Gregorio | deeb020 | 2011-02-15 14:49:57 -0500 | [diff] [blame] | 177 | class Storage(object): |
| 178 | """Base class for all Storage objects. |
| 179 | |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 180 | Store and retrieve a single credential. This class supports locking |
| 181 | such that multiple processes and threads can operate on a single |
| 182 | store. |
Joe Gregorio | deeb020 | 2011-02-15 14:49:57 -0500 | [diff] [blame] | 183 | """ |
| 184 | |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 185 | def acquire_lock(self): |
| 186 | """Acquires any lock necessary to access this Storage. |
| 187 | |
| 188 | This lock is not reentrant.""" |
| 189 | pass |
| 190 | |
| 191 | def release_lock(self): |
| 192 | """Release the Storage lock. |
| 193 | |
| 194 | Trying to release a lock that isn't held will result in a |
| 195 | RuntimeError. |
| 196 | """ |
| 197 | pass |
| 198 | |
| 199 | def locked_get(self): |
Joe Gregorio | deeb020 | 2011-02-15 14:49:57 -0500 | [diff] [blame] | 200 | """Retrieve credential. |
| 201 | |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 202 | The Storage lock must be held when this is called. |
| 203 | |
Joe Gregorio | deeb020 | 2011-02-15 14:49:57 -0500 | [diff] [blame] | 204 | Returns: |
Joe Gregorio | 06d852b | 2011-03-25 15:03:10 -0400 | [diff] [blame] | 205 | oauth2client.client.Credentials |
Joe Gregorio | deeb020 | 2011-02-15 14:49:57 -0500 | [diff] [blame] | 206 | """ |
| 207 | _abstract() |
| 208 | |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 209 | def locked_put(self, credentials): |
Joe Gregorio | deeb020 | 2011-02-15 14:49:57 -0500 | [diff] [blame] | 210 | """Write a credential. |
| 211 | |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 212 | The Storage lock must be held when this is called. |
| 213 | |
Joe Gregorio | deeb020 | 2011-02-15 14:49:57 -0500 | [diff] [blame] | 214 | Args: |
| 215 | credentials: Credentials, the credentials to store. |
| 216 | """ |
| 217 | _abstract() |
| 218 | |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 219 | def get(self): |
| 220 | """Retrieve credential. |
| 221 | |
| 222 | The Storage lock must *not* be held when this is called. |
| 223 | |
| 224 | Returns: |
| 225 | oauth2client.client.Credentials |
| 226 | """ |
| 227 | self.acquire_lock() |
| 228 | try: |
| 229 | return self.locked_get() |
| 230 | finally: |
| 231 | self.release_lock() |
| 232 | |
| 233 | def put(self, credentials): |
| 234 | """Write a credential. |
| 235 | |
| 236 | The Storage lock must be held when this is called. |
| 237 | |
| 238 | Args: |
| 239 | credentials: Credentials, the credentials to store. |
| 240 | """ |
| 241 | self.acquire_lock() |
| 242 | try: |
| 243 | self.locked_put(credentials) |
| 244 | finally: |
| 245 | self.release_lock() |
| 246 | |
Joe Gregorio | deeb020 | 2011-02-15 14:49:57 -0500 | [diff] [blame] | 247 | |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 248 | class OAuth2Credentials(Credentials): |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 249 | """Credentials object for OAuth 2.0. |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 250 | |
Joe Gregorio | 3b79fa8 | 2011-02-17 11:47:17 -0500 | [diff] [blame] | 251 | Credentials can be applied to an httplib2.Http object using the authorize() |
Joe Gregorio | 8b4c173 | 2011-12-06 11:28:29 -0500 | [diff] [blame] | 252 | method, which then adds the OAuth 2.0 access token to each request. |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 253 | |
| 254 | OAuth2Credentials objects may be safely pickled and unpickled. |
| 255 | """ |
| 256 | |
| 257 | def __init__(self, access_token, client_id, client_secret, refresh_token, |
Joe Gregorio | 8b4c173 | 2011-12-06 11:28:29 -0500 | [diff] [blame] | 258 | token_expiry, token_uri, user_agent, id_token=None): |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 259 | """Create an instance of OAuth2Credentials. |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 260 | |
| 261 | This constructor is not usually called by the user, instead |
Joe Gregorio | 3b79fa8 | 2011-02-17 11:47:17 -0500 | [diff] [blame] | 262 | OAuth2Credentials objects are instantiated by the OAuth2WebServerFlow. |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 263 | |
| 264 | Args: |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 265 | access_token: string, access token. |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 266 | client_id: string, client identifier. |
| 267 | client_secret: string, client secret. |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 268 | refresh_token: string, refresh token. |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 269 | token_expiry: datetime, when the access_token expires. |
| 270 | token_uri: string, URI of token endpoint. |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 271 | user_agent: string, The HTTP User-Agent to provide for this application. |
Joe Gregorio | 8b4c173 | 2011-12-06 11:28:29 -0500 | [diff] [blame] | 272 | id_token: object, The identity of the resource owner. |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 273 | |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 274 | Notes: |
Joe Gregorio | 8b4c173 | 2011-12-06 11:28:29 -0500 | [diff] [blame] | 275 | store: callable, A callable that when passed a Credential |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 276 | will store the credential back to where it came from. |
| 277 | This is needed to store the latest access_token if it |
| 278 | has expired and been refreshed. |
| 279 | """ |
| 280 | self.access_token = access_token |
| 281 | self.client_id = client_id |
| 282 | self.client_secret = client_secret |
| 283 | self.refresh_token = refresh_token |
| 284 | self.store = None |
| 285 | self.token_expiry = token_expiry |
| 286 | self.token_uri = token_uri |
| 287 | self.user_agent = user_agent |
Joe Gregorio | 8b4c173 | 2011-12-06 11:28:29 -0500 | [diff] [blame] | 288 | self.id_token = id_token |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 289 | |
Joe Gregorio | 3b79fa8 | 2011-02-17 11:47:17 -0500 | [diff] [blame] | 290 | # True if the credentials have been revoked or expired and can't be |
| 291 | # refreshed. |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 292 | self.invalid = False |
Joe Gregorio | 9ce4b62 | 2011-02-17 15:32:11 -0500 | [diff] [blame] | 293 | |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 294 | def to_json(self): |
| 295 | return self._to_json(Credentials.NON_SERIALIZED_MEMBERS) |
| 296 | |
| 297 | @classmethod |
| 298 | def from_json(cls, s): |
| 299 | """Instantiate a Credentials object from a JSON description of it. The JSON |
| 300 | should have been produced by calling .to_json() on the object. |
| 301 | |
| 302 | Args: |
| 303 | data: dict, A deserialized JSON object. |
| 304 | |
| 305 | Returns: |
| 306 | An instance of a Credentials subclass. |
| 307 | """ |
| 308 | data = simplejson.loads(s) |
| 309 | if 'token_expiry' in data and not isinstance(data['token_expiry'], |
| 310 | datetime.datetime): |
Joe Gregorio | 1daa71b | 2011-09-15 18:12:14 -0400 | [diff] [blame] | 311 | try: |
| 312 | data['token_expiry'] = datetime.datetime.strptime( |
| 313 | data['token_expiry'], EXPIRY_FORMAT) |
| 314 | except: |
| 315 | data['token_expiry'] = None |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 316 | retval = OAuth2Credentials( |
| 317 | data['access_token'], |
| 318 | data['client_id'], |
| 319 | data['client_secret'], |
| 320 | data['refresh_token'], |
| 321 | data['token_expiry'], |
| 322 | data['token_uri'], |
Joe Gregorio | 8b4c173 | 2011-12-06 11:28:29 -0500 | [diff] [blame] | 323 | data['user_agent'], |
| 324 | data.get('id_token', None)) |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 325 | retval.invalid = data['invalid'] |
| 326 | return retval |
| 327 | |
Joe Gregorio | 9ce4b62 | 2011-02-17 15:32:11 -0500 | [diff] [blame] | 328 | @property |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 329 | def access_token_expired(self): |
| 330 | """True if the credential is expired or invalid. |
| 331 | |
| 332 | If the token_expiry isn't set, we assume the token doesn't expire. |
| 333 | """ |
| 334 | if self.invalid: |
| 335 | return True |
| 336 | |
| 337 | if not self.token_expiry: |
| 338 | return False |
| 339 | |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 340 | now = datetime.datetime.utcnow() |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 341 | if now >= self.token_expiry: |
| 342 | logger.info('access_token is expired. Now: %s, token_expiry: %s', |
| 343 | now, self.token_expiry) |
| 344 | return True |
| 345 | return False |
Joe Gregorio | 3b79fa8 | 2011-02-17 11:47:17 -0500 | [diff] [blame] | 346 | |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 347 | def set_store(self, store): |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 348 | """Set the Storage for the credential. |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 349 | |
| 350 | Args: |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 351 | store: Storage, an implementation of Stroage object. |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 352 | This is needed to store the latest access_token if it |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 353 | has expired and been refreshed. This implementation uses |
| 354 | locking to check for updates before updating the |
| 355 | access_token. |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 356 | """ |
| 357 | self.store = store |
| 358 | |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 359 | def _updateFromCredential(self, other): |
| 360 | """Update this Credential from another instance.""" |
| 361 | self.__dict__.update(other.__getstate__()) |
| 362 | |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 363 | def __getstate__(self): |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 364 | """Trim the state down to something that can be pickled.""" |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 365 | d = copy.copy(self.__dict__) |
| 366 | del d['store'] |
| 367 | return d |
| 368 | |
| 369 | def __setstate__(self, state): |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 370 | """Reconstitute the state of the object from being pickled.""" |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 371 | self.__dict__.update(state) |
| 372 | self.store = None |
| 373 | |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 374 | def _generate_refresh_request_body(self): |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 375 | """Generate the body that will be used in the refresh request.""" |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 376 | body = urllib.urlencode({ |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 377 | 'grant_type': 'refresh_token', |
| 378 | 'client_id': self.client_id, |
| 379 | 'client_secret': self.client_secret, |
| 380 | 'refresh_token': self.refresh_token, |
| 381 | }) |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 382 | return body |
| 383 | |
| 384 | def _generate_refresh_request_headers(self): |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 385 | """Generate the headers that will be used in the refresh request.""" |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 386 | headers = { |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 387 | 'content-type': 'application/x-www-form-urlencoded', |
| 388 | } |
JacobMoshenko | cb6d891 | 2011-07-08 13:35:15 -0400 | [diff] [blame] | 389 | |
| 390 | if self.user_agent is not None: |
| 391 | headers['user-agent'] = self.user_agent |
| 392 | |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 393 | return headers |
| 394 | |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 395 | def _refresh(self, http_request): |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 396 | """Refreshes the access_token. |
| 397 | |
| 398 | This method first checks by reading the Storage object if available. |
| 399 | If a refresh is still needed, it holds the Storage lock until the |
| 400 | refresh is completed. |
| 401 | """ |
| 402 | if not self.store: |
| 403 | self._do_refresh_request(http_request) |
| 404 | else: |
| 405 | self.store.acquire_lock() |
| 406 | try: |
| 407 | new_cred = self.store.locked_get() |
| 408 | if (new_cred and not new_cred.invalid and |
| 409 | new_cred.access_token != self.access_token): |
| 410 | logger.info('Updated access_token read from Storage') |
| 411 | self._updateFromCredential(new_cred) |
| 412 | else: |
| 413 | self._do_refresh_request(http_request) |
| 414 | finally: |
| 415 | self.store.release_lock() |
| 416 | |
| 417 | def _do_refresh_request(self, http_request): |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 418 | """Refresh the access_token using the refresh_token. |
| 419 | |
| 420 | Args: |
| 421 | http: An instance of httplib2.Http.request |
| 422 | or something that acts like it. |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 423 | |
| 424 | Raises: |
| 425 | AccessTokenRefreshError: When the refresh fails. |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 426 | """ |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 427 | body = self._generate_refresh_request_body() |
| 428 | headers = self._generate_refresh_request_headers() |
| 429 | |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 430 | logger.info('Refresing access_token') |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 431 | resp, content = http_request( |
| 432 | self.token_uri, method='POST', body=body, headers=headers) |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 433 | if resp.status == 200: |
| 434 | # TODO(jcgregorio) Raise an error if loads fails? |
| 435 | d = simplejson.loads(content) |
| 436 | self.access_token = d['access_token'] |
| 437 | self.refresh_token = d.get('refresh_token', self.refresh_token) |
| 438 | if 'expires_in' in d: |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 439 | self.token_expiry = datetime.timedelta( |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 440 | seconds=int(d['expires_in'])) + datetime.datetime.utcnow() |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 441 | else: |
| 442 | self.token_expiry = None |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 443 | if self.store: |
| 444 | self.store.locked_put(self) |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 445 | else: |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 446 | # An {'error':...} response body means the token is expired or revoked, |
| 447 | # so we flag the credentials as such. |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 448 | logger.error('Failed to retrieve access token: %s' % content) |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 449 | error_msg = 'Invalid response %s.' % resp['status'] |
Joe Gregorio | 3b79fa8 | 2011-02-17 11:47:17 -0500 | [diff] [blame] | 450 | try: |
| 451 | d = simplejson.loads(content) |
| 452 | if 'error' in d: |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 453 | error_msg = d['error'] |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 454 | self.invalid = True |
| 455 | if self.store: |
| 456 | self.store.locked_put(self) |
Joe Gregorio | 3b79fa8 | 2011-02-17 11:47:17 -0500 | [diff] [blame] | 457 | except: |
| 458 | pass |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 459 | raise AccessTokenRefreshError(error_msg) |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 460 | |
| 461 | def authorize(self, http): |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 462 | """Authorize an httplib2.Http instance with these credentials. |
| 463 | |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 464 | Args: |
| 465 | http: An instance of httplib2.Http |
| 466 | or something that acts like it. |
| 467 | |
| 468 | Returns: |
| 469 | A modified instance of http that was passed in. |
| 470 | |
| 471 | Example: |
| 472 | |
| 473 | h = httplib2.Http() |
| 474 | h = credentials.authorize(h) |
| 475 | |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 476 | You can't create a new OAuth subclass of httplib2.Authenication |
| 477 | because it never gets passed the absolute URI, which is needed for |
| 478 | signing. So instead we have to overload 'request' with a closure |
| 479 | that adds in the Authorization header and then calls the original |
| 480 | version of 'request()'. |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 481 | """ |
| 482 | request_orig = http.request |
| 483 | |
| 484 | # The closure that will replace 'httplib2.Http.request'. |
| 485 | def new_request(uri, method='GET', body=None, headers=None, |
| 486 | redirections=httplib2.DEFAULT_MAX_REDIRECTS, |
| 487 | connection_type=None): |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 488 | if not self.access_token: |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 489 | logger.info('Attempting refresh to obtain initial access_token') |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 490 | self._refresh(request_orig) |
| 491 | |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 492 | # Modify the request headers to add the appropriate |
| 493 | # Authorization header. |
| 494 | if headers is None: |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 495 | headers = {} |
Joe Gregorio | 49e94d8 | 2011-01-28 16:36:13 -0500 | [diff] [blame] | 496 | headers['authorization'] = 'OAuth ' + self.access_token |
JacobMoshenko | cb6d891 | 2011-07-08 13:35:15 -0400 | [diff] [blame] | 497 | |
| 498 | if self.user_agent is not None: |
| 499 | if 'user-agent' in headers: |
| 500 | headers['user-agent'] = self.user_agent + ' ' + headers['user-agent'] |
| 501 | else: |
| 502 | headers['user-agent'] = self.user_agent |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 503 | |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 504 | resp, content = request_orig(uri, method, body, headers, |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 505 | redirections, connection_type) |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 506 | |
Joe Gregorio | fd19cd3 | 2011-01-20 11:37:29 -0500 | [diff] [blame] | 507 | if resp.status == 401: |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 508 | logger.info('Refreshing due to a 401') |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 509 | self._refresh(request_orig) |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 510 | headers['authorization'] = 'OAuth ' + self.access_token |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 511 | return request_orig(uri, method, body, headers, |
| 512 | redirections, connection_type) |
| 513 | else: |
| 514 | return (resp, content) |
| 515 | |
| 516 | http.request = new_request |
| 517 | return http |
| 518 | |
| 519 | |
Joe Gregorio | 3b79fa8 | 2011-02-17 11:47:17 -0500 | [diff] [blame] | 520 | class AccessTokenCredentials(OAuth2Credentials): |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 521 | """Credentials object for OAuth 2.0. |
Joe Gregorio | 3b79fa8 | 2011-02-17 11:47:17 -0500 | [diff] [blame] | 522 | |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 523 | Credentials can be applied to an httplib2.Http object using the |
| 524 | authorize() method, which then signs each request from that object |
| 525 | with the OAuth 2.0 access token. This set of credentials is for the |
| 526 | use case where you have acquired an OAuth 2.0 access_token from |
| 527 | another place such as a JavaScript client or another web |
| 528 | application, and wish to use it from Python. Because only the |
| 529 | access_token is present it can not be refreshed and will in time |
Joe Gregorio | 3b79fa8 | 2011-02-17 11:47:17 -0500 | [diff] [blame] | 530 | expire. |
| 531 | |
Joe Gregorio | 9ce4b62 | 2011-02-17 15:32:11 -0500 | [diff] [blame] | 532 | AccessTokenCredentials objects may be safely pickled and unpickled. |
Joe Gregorio | 3b79fa8 | 2011-02-17 11:47:17 -0500 | [diff] [blame] | 533 | |
| 534 | Usage: |
| 535 | credentials = AccessTokenCredentials('<an access token>', |
| 536 | 'my-user-agent/1.0') |
| 537 | http = httplib2.Http() |
| 538 | http = credentials.authorize(http) |
| 539 | |
| 540 | Exceptions: |
| 541 | AccessTokenCredentialsExpired: raised when the access_token expires or is |
| 542 | revoked. |
Joe Gregorio | 3b79fa8 | 2011-02-17 11:47:17 -0500 | [diff] [blame] | 543 | """ |
| 544 | |
| 545 | def __init__(self, access_token, user_agent): |
| 546 | """Create an instance of OAuth2Credentials |
| 547 | |
| 548 | This is one of the few types if Credentials that you should contrust, |
| 549 | Credentials objects are usually instantiated by a Flow. |
| 550 | |
| 551 | Args: |
ade@google.com | 93a7f7c | 2011-02-23 16:00:37 +0000 | [diff] [blame] | 552 | access_token: string, access token. |
Joe Gregorio | 3b79fa8 | 2011-02-17 11:47:17 -0500 | [diff] [blame] | 553 | user_agent: string, The HTTP User-Agent to provide for this application. |
| 554 | |
| 555 | Notes: |
| 556 | store: callable, a callable that when passed a Credential |
| 557 | will store the credential back to where it came from. |
| 558 | """ |
| 559 | super(AccessTokenCredentials, self).__init__( |
| 560 | access_token, |
| 561 | None, |
| 562 | None, |
| 563 | None, |
| 564 | None, |
| 565 | None, |
| 566 | user_agent) |
| 567 | |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 568 | |
| 569 | @classmethod |
| 570 | def from_json(cls, s): |
| 571 | data = simplejson.loads(s) |
| 572 | retval = AccessTokenCredentials( |
| 573 | data['access_token'], |
| 574 | data['user_agent']) |
| 575 | return retval |
| 576 | |
Joe Gregorio | 3b79fa8 | 2011-02-17 11:47:17 -0500 | [diff] [blame] | 577 | def _refresh(self, http_request): |
| 578 | raise AccessTokenCredentialsError( |
| 579 | "The access_token is expired or invalid and can't be refreshed.") |
| 580 | |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 581 | |
| 582 | class AssertionCredentials(OAuth2Credentials): |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 583 | """Abstract Credentials object used for OAuth 2.0 assertion grants. |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 584 | |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 585 | This credential does not require a flow to instantiate because it |
| 586 | represents a two legged flow, and therefore has all of the required |
| 587 | information to generate and refresh its own access tokens. It must |
| 588 | be subclassed to generate the appropriate assertion string. |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 589 | |
| 590 | AssertionCredentials objects may be safely pickled and unpickled. |
| 591 | """ |
| 592 | |
| 593 | def __init__(self, assertion_type, user_agent, |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 594 | token_uri='https://accounts.google.com/o/oauth2/token', |
| 595 | **unused_kwargs): |
| 596 | """Constructor for AssertionFlowCredentials. |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 597 | |
| 598 | Args: |
| 599 | assertion_type: string, assertion type that will be declared to the auth |
| 600 | server |
| 601 | user_agent: string, The HTTP User-Agent to provide for this application. |
| 602 | token_uri: string, URI for token endpoint. For convenience |
| 603 | defaults to Google's endpoints but any OAuth 2.0 provider can be used. |
| 604 | """ |
| 605 | super(AssertionCredentials, self).__init__( |
| 606 | None, |
| 607 | None, |
| 608 | None, |
| 609 | None, |
| 610 | None, |
| 611 | token_uri, |
| 612 | user_agent) |
| 613 | self.assertion_type = assertion_type |
| 614 | |
| 615 | def _generate_refresh_request_body(self): |
| 616 | assertion = self._generate_assertion() |
| 617 | |
| 618 | body = urllib.urlencode({ |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 619 | 'assertion_type': self.assertion_type, |
| 620 | 'assertion': assertion, |
| 621 | 'grant_type': 'assertion', |
| 622 | }) |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 623 | |
| 624 | return body |
| 625 | |
| 626 | def _generate_assertion(self): |
| 627 | """Generate the assertion string that will be used in the access token |
| 628 | request. |
| 629 | """ |
| 630 | _abstract() |
| 631 | |
Joe Gregorio | 8b4c173 | 2011-12-06 11:28:29 -0500 | [diff] [blame] | 632 | if HAS_OPENSSL: |
| 633 | # PyOpenSSL is not a prerequisite for oauth2client, so if it is missing then |
| 634 | # don't create the SignedJwtAssertionCredentials or the verify_id_token() |
| 635 | # method. |
| 636 | |
| 637 | class SignedJwtAssertionCredentials(AssertionCredentials): |
| 638 | """Credentials object used for OAuth 2.0 Signed JWT assertion grants. |
| 639 | |
| 640 | This credential does not require a flow to instantiate because it |
| 641 | represents a two legged flow, and therefore has all of the required |
| 642 | information to generate and refresh its own access tokens. |
| 643 | """ |
| 644 | |
| 645 | MAX_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds |
| 646 | |
| 647 | def __init__(self, |
| 648 | service_account_name, |
| 649 | private_key, |
| 650 | scope, |
| 651 | private_key_password='notasecret', |
| 652 | user_agent=None, |
| 653 | token_uri='https://accounts.google.com/o/oauth2/token', |
| 654 | **kwargs): |
| 655 | """Constructor for SignedJwtAssertionCredentials. |
| 656 | |
| 657 | Args: |
| 658 | service_account_name: string, id for account, usually an email address. |
| 659 | private_key: string, private key in P12 format. |
| 660 | scope: string or list of strings, scope(s) of the credentials being |
| 661 | requested. |
| 662 | private_key_password: string, password for private_key. |
| 663 | user_agent: string, HTTP User-Agent to provide for this application. |
| 664 | token_uri: string, URI for token endpoint. For convenience |
| 665 | defaults to Google's endpoints but any OAuth 2.0 provider can be used. |
| 666 | kwargs: kwargs, Additional parameters to add to the JWT token, for |
| 667 | example prn=joe@xample.org.""" |
| 668 | |
| 669 | super(SignedJwtAssertionCredentials, self).__init__( |
| 670 | 'http://oauth.net/grant_type/jwt/1.0/bearer', |
| 671 | user_agent, |
| 672 | token_uri=token_uri, |
| 673 | ) |
| 674 | |
| 675 | if type(scope) is list: |
| 676 | scope = ' '.join(scope) |
| 677 | self.scope = scope |
| 678 | |
| 679 | self.private_key = private_key |
| 680 | self.private_key_password = private_key_password |
| 681 | self.service_account_name = service_account_name |
| 682 | self.kwargs = kwargs |
| 683 | |
| 684 | @classmethod |
| 685 | def from_json(cls, s): |
| 686 | data = simplejson.loads(s) |
| 687 | retval = SignedJwtAssertionCredentials( |
| 688 | data['service_account_name'], |
| 689 | data['private_key'], |
| 690 | data['private_key_password'], |
| 691 | data['scope'], |
| 692 | data['user_agent'], |
| 693 | data['token_uri'], |
| 694 | data['kwargs'] |
| 695 | ) |
| 696 | retval.invalid = data['invalid'] |
| 697 | return retval |
| 698 | |
| 699 | def _generate_assertion(self): |
| 700 | """Generate the assertion that will be used in the request.""" |
| 701 | now = long(time.time()) |
| 702 | payload = { |
| 703 | 'aud': self.token_uri, |
| 704 | 'scope': self.scope, |
| 705 | 'iat': now, |
| 706 | 'exp': now + SignedJwtAssertionCredentials.MAX_TOKEN_LIFETIME_SECS, |
| 707 | 'iss': self.service_account_name |
| 708 | } |
| 709 | payload.update(self.kwargs) |
| 710 | logging.debug(str(payload)) |
| 711 | |
| 712 | return make_signed_jwt( |
| 713 | Signer.from_string(self.private_key, self.private_key_password), |
| 714 | payload) |
| 715 | |
| 716 | |
| 717 | def verify_id_token(id_token, audience, http=None, |
| 718 | cert_uri=ID_TOKEN_VERIFICATON_CERTS): |
| 719 | """Verifies a signed JWT id_token. |
| 720 | |
| 721 | Args: |
| 722 | id_token: string, A Signed JWT. |
| 723 | audience: string, The audience 'aud' that the token should be for. |
| 724 | http: httplib2.Http, instance to use to make the HTTP request. Callers |
| 725 | should supply an instance that has caching enabled. |
| 726 | cert_uri: string, URI of the certificates in JSON format to |
| 727 | verify the JWT against. |
| 728 | |
| 729 | Returns: |
| 730 | The deserialized JSON in the JWT. |
| 731 | |
| 732 | Raises: |
| 733 | oauth2client.crypt.AppIdentityError if the JWT fails to verify. |
| 734 | """ |
| 735 | if http is None: |
| 736 | http = CACHED_HTTP |
| 737 | |
| 738 | resp, content = http.request(cert_uri) |
| 739 | |
| 740 | if resp.status == 200: |
| 741 | certs = simplejson.loads(content) |
| 742 | return verify_signed_jwt_with_certs(id_token, certs, audience) |
| 743 | else: |
| 744 | raise VerifyJwtTokenError('Status code: %d' % resp.status) |
| 745 | |
| 746 | |
| 747 | def _urlsafe_b64decode(b64string): |
Joe Gregorio | bd512b5 | 2011-12-06 15:39:26 -0500 | [diff] [blame] | 748 | # Guard against unicode strings, which base64 can't handle. |
| 749 | b64string = b64string.encode('ascii') |
Joe Gregorio | 8b4c173 | 2011-12-06 11:28:29 -0500 | [diff] [blame] | 750 | padded = b64string + '=' * (4 - len(b64string) % 4) |
| 751 | return base64.urlsafe_b64decode(padded) |
| 752 | |
| 753 | |
| 754 | def _extract_id_token(id_token): |
| 755 | """Extract the JSON payload from a JWT. |
| 756 | |
| 757 | Does the extraction w/o checking the signature. |
| 758 | |
| 759 | Args: |
| 760 | id_token: string, OAuth 2.0 id_token. |
| 761 | |
| 762 | Returns: |
| 763 | object, The deserialized JSON payload. |
| 764 | """ |
| 765 | segments = id_token.split('.') |
| 766 | |
| 767 | if (len(segments) != 3): |
| 768 | raise VerifyJwtTokenError( |
| 769 | 'Wrong number of segments in token: %s' % id_token) |
| 770 | |
| 771 | return simplejson.loads(_urlsafe_b64decode(segments[1])) |
| 772 | |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 773 | |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 774 | class OAuth2WebServerFlow(Flow): |
| 775 | """Does the Web Server Flow for OAuth 2.0. |
| 776 | |
| 777 | OAuth2Credentials objects may be safely pickled and unpickled. |
| 778 | """ |
| 779 | |
Joe Gregorio | f08a498 | 2011-10-07 13:11:16 -0400 | [diff] [blame] | 780 | def __init__(self, client_id, client_secret, scope, user_agent=None, |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 781 | auth_uri='https://accounts.google.com/o/oauth2/auth', |
| 782 | token_uri='https://accounts.google.com/o/oauth2/token', |
| 783 | **kwargs): |
| 784 | """Constructor for OAuth2WebServerFlow. |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 785 | |
| 786 | Args: |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 787 | client_id: string, client identifier. |
| 788 | client_secret: string client secret. |
Joe Gregorio | f2f8a5a | 2011-10-14 15:11:29 -0400 | [diff] [blame] | 789 | scope: string or list of strings, scope(s) of the credentials being |
| 790 | requested. |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 791 | user_agent: string, HTTP User-Agent to provide for this application. |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 792 | auth_uri: string, URI for authorization endpoint. For convenience |
| 793 | defaults to Google's endpoints but any OAuth 2.0 provider can be used. |
| 794 | token_uri: string, URI for token endpoint. For convenience |
| 795 | defaults to Google's endpoints but any OAuth 2.0 provider can be used. |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 796 | **kwargs: dict, The keyword arguments are all optional and required |
| 797 | parameters for the OAuth calls. |
| 798 | """ |
| 799 | self.client_id = client_id |
| 800 | self.client_secret = client_secret |
Joe Gregorio | f2f8a5a | 2011-10-14 15:11:29 -0400 | [diff] [blame] | 801 | if type(scope) is list: |
| 802 | scope = ' '.join(scope) |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 803 | self.scope = scope |
| 804 | self.user_agent = user_agent |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 805 | self.auth_uri = auth_uri |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 806 | self.token_uri = token_uri |
Joe Gregorio | 69a0aca | 2011-11-03 10:47:32 -0400 | [diff] [blame] | 807 | self.params = { |
| 808 | 'access_type': 'offline', |
| 809 | } |
| 810 | self.params.update(kwargs) |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 811 | self.redirect_uri = None |
| 812 | |
| 813 | def step1_get_authorize_url(self, redirect_uri='oob'): |
| 814 | """Returns a URI to redirect to the provider. |
| 815 | |
| 816 | Args: |
| 817 | redirect_uri: string, Either the string 'oob' for a non-web-based |
| 818 | application, or a URI that handles the callback from |
| 819 | the authorization server. |
| 820 | |
| 821 | If redirect_uri is 'oob' then pass in the |
| 822 | generated verification code to step2_exchange, |
| 823 | otherwise pass in the query parameters received |
| 824 | at the callback uri to step2_exchange. |
| 825 | """ |
| 826 | |
| 827 | self.redirect_uri = redirect_uri |
| 828 | query = { |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 829 | 'response_type': 'code', |
| 830 | 'client_id': self.client_id, |
| 831 | 'redirect_uri': redirect_uri, |
| 832 | 'scope': self.scope, |
| 833 | } |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 834 | query.update(self.params) |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 835 | parts = list(urlparse.urlparse(self.auth_uri)) |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 836 | query.update(dict(parse_qsl(parts[4]))) # 4 is the index of the query part |
| 837 | parts[4] = urllib.urlencode(query) |
| 838 | return urlparse.urlunparse(parts) |
| 839 | |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 840 | def step2_exchange(self, code, http=None): |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 841 | """Exhanges a code for OAuth2Credentials. |
| 842 | |
| 843 | Args: |
| 844 | code: string or dict, either the code as a string, or a dictionary |
| 845 | of the query parameters to the redirect_uri, which contains |
| 846 | the code. |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 847 | http: httplib2.Http, optional http instance to use to do the fetch |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 848 | """ |
| 849 | |
| 850 | if not (isinstance(code, str) or isinstance(code, unicode)): |
| 851 | code = code['code'] |
| 852 | |
| 853 | body = urllib.urlencode({ |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 854 | 'grant_type': 'authorization_code', |
| 855 | 'client_id': self.client_id, |
| 856 | 'client_secret': self.client_secret, |
| 857 | 'code': code, |
| 858 | 'redirect_uri': self.redirect_uri, |
| 859 | 'scope': self.scope, |
| 860 | }) |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 861 | headers = { |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 862 | 'content-type': 'application/x-www-form-urlencoded', |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 863 | } |
JacobMoshenko | cb6d891 | 2011-07-08 13:35:15 -0400 | [diff] [blame] | 864 | |
| 865 | if self.user_agent is not None: |
| 866 | headers['user-agent'] = self.user_agent |
| 867 | |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 868 | if http is None: |
| 869 | http = httplib2.Http() |
Joe Gregorio | 8b4c173 | 2011-12-06 11:28:29 -0500 | [diff] [blame] | 870 | |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 871 | resp, content = http.request(self.token_uri, method='POST', body=body, |
| 872 | headers=headers) |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 873 | if resp.status == 200: |
| 874 | # TODO(jcgregorio) Raise an error if simplejson.loads fails? |
| 875 | d = simplejson.loads(content) |
| 876 | access_token = d['access_token'] |
| 877 | refresh_token = d.get('refresh_token', None) |
| 878 | token_expiry = None |
| 879 | if 'expires_in' in d: |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 880 | token_expiry = datetime.datetime.utcnow() + datetime.timedelta( |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 881 | seconds=int(d['expires_in'])) |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 882 | |
Joe Gregorio | 8b4c173 | 2011-12-06 11:28:29 -0500 | [diff] [blame] | 883 | if 'id_token' in d: |
| 884 | d['id_token'] = _extract_id_token(d['id_token']) |
| 885 | |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 886 | logger.info('Successfully retrieved access token: %s' % content) |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 887 | return OAuth2Credentials(access_token, self.client_id, |
| 888 | self.client_secret, refresh_token, token_expiry, |
Joe Gregorio | 8b4c173 | 2011-12-06 11:28:29 -0500 | [diff] [blame] | 889 | self.token_uri, self.user_agent, |
| 890 | id_token=d.get('id_token', None)) |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 891 | else: |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 892 | logger.error('Failed to retrieve access token: %s' % content) |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 893 | error_msg = 'Invalid response %s.' % resp['status'] |
| 894 | try: |
| 895 | d = simplejson.loads(content) |
| 896 | if 'error' in d: |
| 897 | error_msg = d['error'] |
| 898 | except: |
| 899 | pass |
| 900 | |
| 901 | raise FlowExchangeError(error_msg) |
Joe Gregorio | f08a498 | 2011-10-07 13:11:16 -0400 | [diff] [blame] | 902 | |
| 903 | def flow_from_clientsecrets(filename, scope, message=None): |
| 904 | """Create a Flow from a clientsecrets file. |
| 905 | |
| 906 | Will create the right kind of Flow based on the contents of the clientsecrets |
| 907 | file or will raise InvalidClientSecretsError for unknown types of Flows. |
| 908 | |
| 909 | Args: |
| 910 | filename: string, File name of client secrets. |
Joe Gregorio | f2f8a5a | 2011-10-14 15:11:29 -0400 | [diff] [blame] | 911 | scope: string or list of strings, scope(s) to request. |
Joe Gregorio | f08a498 | 2011-10-07 13:11:16 -0400 | [diff] [blame] | 912 | message: string, A friendly string to display to the user if the |
| 913 | clientsecrets file is missing or invalid. If message is provided then |
| 914 | sys.exit will be called in the case of an error. If message in not |
| 915 | provided then clientsecrets.InvalidClientSecretsError will be raised. |
| 916 | |
| 917 | Returns: |
| 918 | A Flow object. |
| 919 | |
| 920 | Raises: |
| 921 | UnknownClientSecretsFlowError if the file describes an unknown kind of Flow. |
| 922 | clientsecrets.InvalidClientSecretsError if the clientsecrets file is |
| 923 | invalid. |
| 924 | """ |
Joe Gregorio | 0984ef2 | 2011-10-14 13:17:43 -0400 | [diff] [blame] | 925 | try: |
| 926 | client_type, client_info = clientsecrets.loadfile(filename) |
| 927 | if client_type in [clientsecrets.TYPE_WEB, clientsecrets.TYPE_INSTALLED]: |
| 928 | return OAuth2WebServerFlow( |
| 929 | client_info['client_id'], |
| 930 | client_info['client_secret'], |
| 931 | scope, |
| 932 | None, # user_agent |
| 933 | client_info['auth_uri'], |
| 934 | client_info['token_uri']) |
| 935 | except clientsecrets.InvalidClientSecretsError: |
| 936 | if message: |
| 937 | sys.exit(message) |
| 938 | else: |
| 939 | raise |
Joe Gregorio | f08a498 | 2011-10-07 13:11:16 -0400 | [diff] [blame] | 940 | else: |
| 941 | raise UnknownClientSecretsFlowError( |
| 942 | 'This OAuth 2.0 flow is unsupported: "%s"' * client_type) |