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