Jon Wayne Parrott | 10ec7e9 | 2016-10-17 10:46:38 -0700 | [diff] [blame] | 1 | # Copyright 2016 Google Inc. |
| 2 | # |
| 3 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | # you may not use this file except in compliance with the License. |
| 5 | # You may obtain a copy of the License at |
| 6 | # |
| 7 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | # |
| 9 | # Unless required by applicable law or agreed to in writing, software |
| 10 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | # See the License for the specific language governing permissions and |
| 13 | # limitations under the License. |
| 14 | |
| 15 | """OAuth 2.0 Credentials. |
| 16 | |
| 17 | This module provides credentials based on OAuth 2.0 access and refresh tokens. |
| 18 | These credentials usually access resources on behalf of a user (resource |
| 19 | owner). |
| 20 | |
| 21 | Specifically, this is intended to use access tokens acquired using the |
| 22 | `Authorization Code grant`_ and can refresh those tokens using a |
| 23 | optional `refresh token`_. |
| 24 | |
| 25 | Obtaining the initial access and refresh token is outside of the scope of this |
| 26 | module. Consult `rfc6749 section 4.1`_ for complete details on the |
| 27 | Authorization Code grant flow. |
| 28 | |
| 29 | .. _Authorization Code grant: https://tools.ietf.org/html/rfc6749#section-1.3.1 |
| 30 | .. _refresh token: https://tools.ietf.org/html/rfc6749#section-6 |
| 31 | .. _rfc6749 section 4.1: https://tools.ietf.org/html/rfc6749#section-4.1 |
| 32 | """ |
| 33 | |
Hiranya Jayathilaka | 23c88f7 | 2017-12-05 09:29:59 -0800 | [diff] [blame] | 34 | import io |
| 35 | import json |
| 36 | |
| 37 | import six |
| 38 | |
Jon Wayne Parrott | 10ec7e9 | 2016-10-17 10:46:38 -0700 | [diff] [blame] | 39 | from google.auth import _helpers |
| 40 | from google.auth import credentials |
Thea Flowers | 118c048 | 2018-05-24 13:34:07 -0700 | [diff] [blame] | 41 | from google.auth import exceptions |
Jon Wayne Parrott | 10ec7e9 | 2016-10-17 10:46:38 -0700 | [diff] [blame] | 42 | from google.oauth2 import _client |
| 43 | |
| 44 | |
Hiranya Jayathilaka | 23c88f7 | 2017-12-05 09:29:59 -0800 | [diff] [blame] | 45 | # The Google OAuth 2.0 token endpoint. Used for authorized user credentials. |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 46 | _GOOGLE_OAUTH2_TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token" |
Hiranya Jayathilaka | 23c88f7 | 2017-12-05 09:29:59 -0800 | [diff] [blame] | 47 | |
| 48 | |
Mahmoud Bassiouny | cb7b3c4 | 2017-09-20 09:01:28 -0700 | [diff] [blame] | 49 | class Credentials(credentials.ReadOnlyScoped, credentials.Credentials): |
Jon Wayne Parrott | 10ec7e9 | 2016-10-17 10:46:38 -0700 | [diff] [blame] | 50 | """Credentials using OAuth 2.0 access and refresh tokens.""" |
| 51 | |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 52 | def __init__( |
| 53 | self, |
| 54 | token, |
| 55 | refresh_token=None, |
| 56 | id_token=None, |
| 57 | token_uri=None, |
| 58 | client_id=None, |
| 59 | client_secret=None, |
| 60 | scopes=None, |
| 61 | ): |
Jon Wayne Parrott | 10ec7e9 | 2016-10-17 10:46:38 -0700 | [diff] [blame] | 62 | """ |
| 63 | Args: |
| 64 | token (Optional(str)): The OAuth 2.0 access token. Can be None |
| 65 | if refresh information is provided. |
| 66 | refresh_token (str): The OAuth 2.0 refresh token. If specified, |
| 67 | credentials can be refreshed. |
Jon Wayne Parrott | 26a1637 | 2017-03-28 13:03:33 -0700 | [diff] [blame] | 68 | id_token (str): The Open ID Connect ID Token. |
Jon Wayne Parrott | 10ec7e9 | 2016-10-17 10:46:38 -0700 | [diff] [blame] | 69 | token_uri (str): The OAuth 2.0 authorization server's token |
| 70 | endpoint URI. Must be specified for refresh, can be left as |
| 71 | None if the token can not be refreshed. |
| 72 | client_id (str): The OAuth 2.0 client ID. Must be specified for |
| 73 | refresh, can be left as None if the token can not be refreshed. |
| 74 | client_secret(str): The OAuth 2.0 client secret. Must be specified |
| 75 | for refresh, can be left as None if the token can not be |
| 76 | refreshed. |
Eugene W. Foley | 49a18c4 | 2019-05-22 13:50:38 -0400 | [diff] [blame] | 77 | scopes (Sequence[str]): The scopes used to obtain authorization. |
| 78 | This parameter is used by :meth:`has_scopes`. OAuth 2.0 |
| 79 | credentials can not request additional scopes after |
| 80 | authorization. The scopes must be derivable from the refresh |
| 81 | token if refresh information is provided (e.g. The refresh |
| 82 | token scopes are a superset of this or contain a wild card |
| 83 | scope like 'https://www.googleapis.com/auth/any-api'). |
Jon Wayne Parrott | 10ec7e9 | 2016-10-17 10:46:38 -0700 | [diff] [blame] | 84 | """ |
| 85 | super(Credentials, self).__init__() |
| 86 | self.token = token |
| 87 | self._refresh_token = refresh_token |
Jon Wayne Parrott | 26a1637 | 2017-03-28 13:03:33 -0700 | [diff] [blame] | 88 | self._id_token = id_token |
Jon Wayne Parrott | 10ec7e9 | 2016-10-17 10:46:38 -0700 | [diff] [blame] | 89 | self._scopes = scopes |
| 90 | self._token_uri = token_uri |
| 91 | self._client_id = client_id |
| 92 | self._client_secret = client_secret |
| 93 | |
| 94 | @property |
Jon Wayne Parrott | 2d0549a | 2017-03-01 09:27:16 -0800 | [diff] [blame] | 95 | def refresh_token(self): |
| 96 | """Optional[str]: The OAuth 2.0 refresh token.""" |
| 97 | return self._refresh_token |
| 98 | |
| 99 | @property |
| 100 | def token_uri(self): |
| 101 | """Optional[str]: The OAuth 2.0 authorization server's token endpoint |
| 102 | URI.""" |
| 103 | return self._token_uri |
| 104 | |
| 105 | @property |
Jon Wayne Parrott | 26a1637 | 2017-03-28 13:03:33 -0700 | [diff] [blame] | 106 | def id_token(self): |
| 107 | """Optional[str]: The Open ID Connect ID Token. |
| 108 | |
| 109 | Depending on the authorization server and the scopes requested, this |
| 110 | may be populated when credentials are obtained and updated when |
| 111 | :meth:`refresh` is called. This token is a JWT. It can be verified |
| 112 | and decoded using :func:`google.oauth2.id_token.verify_oauth2_token`. |
| 113 | """ |
| 114 | return self._id_token |
| 115 | |
| 116 | @property |
Jon Wayne Parrott | 2d0549a | 2017-03-01 09:27:16 -0800 | [diff] [blame] | 117 | def client_id(self): |
| 118 | """Optional[str]: The OAuth 2.0 client ID.""" |
| 119 | return self._client_id |
| 120 | |
| 121 | @property |
| 122 | def client_secret(self): |
| 123 | """Optional[str]: The OAuth 2.0 client secret.""" |
| 124 | return self._client_secret |
| 125 | |
| 126 | @property |
Jon Wayne Parrott | 10ec7e9 | 2016-10-17 10:46:38 -0700 | [diff] [blame] | 127 | def requires_scopes(self): |
| 128 | """False: OAuth 2.0 credentials have their scopes set when |
| 129 | the initial token is requested and can not be changed.""" |
| 130 | return False |
| 131 | |
Jon Wayne Parrott | 10ec7e9 | 2016-10-17 10:46:38 -0700 | [diff] [blame] | 132 | @_helpers.copy_docstring(credentials.Credentials) |
| 133 | def refresh(self, request): |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 134 | if ( |
| 135 | self._refresh_token is None |
| 136 | or self._token_uri is None |
| 137 | or self._client_id is None |
| 138 | or self._client_secret is None |
| 139 | ): |
Thea Flowers | 118c048 | 2018-05-24 13:34:07 -0700 | [diff] [blame] | 140 | raise exceptions.RefreshError( |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 141 | "The credentials do not contain the necessary fields need to " |
| 142 | "refresh the access token. You must specify refresh_token, " |
| 143 | "token_uri, client_id, and client_secret." |
| 144 | ) |
Thea Flowers | 118c048 | 2018-05-24 13:34:07 -0700 | [diff] [blame] | 145 | |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 146 | access_token, refresh_token, expiry, grant_response = _client.refresh_grant( |
| 147 | request, |
| 148 | self._token_uri, |
| 149 | self._refresh_token, |
| 150 | self._client_id, |
| 151 | self._client_secret, |
| 152 | self._scopes, |
| 153 | ) |
Jon Wayne Parrott | 10ec7e9 | 2016-10-17 10:46:38 -0700 | [diff] [blame] | 154 | |
| 155 | self.token = access_token |
| 156 | self.expiry = expiry |
| 157 | self._refresh_token = refresh_token |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 158 | self._id_token = grant_response.get("id_token") |
Hiranya Jayathilaka | 23c88f7 | 2017-12-05 09:29:59 -0800 | [diff] [blame] | 159 | |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 160 | if self._scopes and "scopes" in grant_response: |
Eugene W. Foley | 49a18c4 | 2019-05-22 13:50:38 -0400 | [diff] [blame] | 161 | requested_scopes = frozenset(self._scopes) |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 162 | granted_scopes = frozenset(grant_response["scopes"].split()) |
| 163 | scopes_requested_but_not_granted = requested_scopes - granted_scopes |
Eugene W. Foley | 49a18c4 | 2019-05-22 13:50:38 -0400 | [diff] [blame] | 164 | if scopes_requested_but_not_granted: |
| 165 | raise exceptions.RefreshError( |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 166 | "Not all requested scopes were granted by the " |
| 167 | "authorization server, missing scopes {}.".format( |
| 168 | ", ".join(scopes_requested_but_not_granted) |
| 169 | ) |
| 170 | ) |
Eugene W. Foley | 49a18c4 | 2019-05-22 13:50:38 -0400 | [diff] [blame] | 171 | |
Hiranya Jayathilaka | 23c88f7 | 2017-12-05 09:29:59 -0800 | [diff] [blame] | 172 | @classmethod |
| 173 | def from_authorized_user_info(cls, info, scopes=None): |
| 174 | """Creates a Credentials instance from parsed authorized user info. |
| 175 | |
| 176 | Args: |
| 177 | info (Mapping[str, str]): The authorized user info in Google |
| 178 | format. |
| 179 | scopes (Sequence[str]): Optional list of scopes to include in the |
| 180 | credentials. |
| 181 | |
| 182 | Returns: |
| 183 | google.oauth2.credentials.Credentials: The constructed |
| 184 | credentials. |
| 185 | |
| 186 | Raises: |
| 187 | ValueError: If the info is not in the expected format. |
| 188 | """ |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 189 | keys_needed = set(("refresh_token", "client_id", "client_secret")) |
Hiranya Jayathilaka | 23c88f7 | 2017-12-05 09:29:59 -0800 | [diff] [blame] | 190 | missing = keys_needed.difference(six.iterkeys(info)) |
| 191 | |
| 192 | if missing: |
| 193 | raise ValueError( |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 194 | "Authorized user info was not in the expected format, missing " |
| 195 | "fields {}.".format(", ".join(missing)) |
| 196 | ) |
Hiranya Jayathilaka | 23c88f7 | 2017-12-05 09:29:59 -0800 | [diff] [blame] | 197 | |
Emile Caron | 530f5f9 | 2019-07-26 01:23:25 +0200 | [diff] [blame] | 198 | return cls( |
Hiranya Jayathilaka | 23c88f7 | 2017-12-05 09:29:59 -0800 | [diff] [blame] | 199 | None, # No access token, must be refreshed. |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 200 | refresh_token=info["refresh_token"], |
Hiranya Jayathilaka | 23c88f7 | 2017-12-05 09:29:59 -0800 | [diff] [blame] | 201 | token_uri=_GOOGLE_OAUTH2_TOKEN_ENDPOINT, |
| 202 | scopes=scopes, |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 203 | client_id=info["client_id"], |
| 204 | client_secret=info["client_secret"], |
| 205 | ) |
Hiranya Jayathilaka | 23c88f7 | 2017-12-05 09:29:59 -0800 | [diff] [blame] | 206 | |
| 207 | @classmethod |
| 208 | def from_authorized_user_file(cls, filename, scopes=None): |
| 209 | """Creates a Credentials instance from an authorized user json file. |
| 210 | |
| 211 | Args: |
| 212 | filename (str): The path to the authorized user json file. |
| 213 | scopes (Sequence[str]): Optional list of scopes to include in the |
| 214 | credentials. |
| 215 | |
| 216 | Returns: |
| 217 | google.oauth2.credentials.Credentials: The constructed |
| 218 | credentials. |
| 219 | |
| 220 | Raises: |
| 221 | ValueError: If the file is not in the expected format. |
| 222 | """ |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 223 | with io.open(filename, "r", encoding="utf-8") as json_file: |
Hiranya Jayathilaka | 23c88f7 | 2017-12-05 09:29:59 -0800 | [diff] [blame] | 224 | data = json.load(json_file) |
| 225 | return cls.from_authorized_user_info(data, scopes) |
patkasper | bfb1f8c | 2019-12-05 22:03:44 +0100 | [diff] [blame^] | 226 | |
| 227 | def to_json(self, strip=None): |
| 228 | """Utility function that creates a JSON representation of a Credentials |
| 229 | object. |
| 230 | |
| 231 | Args: |
| 232 | strip (Sequence[str]): Optional list of members to exclude from the |
| 233 | generated JSON. |
| 234 | |
| 235 | Returns: |
| 236 | str: A JSON representation of this instance, suitable to pass to |
| 237 | from_json(). |
| 238 | """ |
| 239 | prep = { |
| 240 | "token": self.token, |
| 241 | "refresh_token": self.refresh_token, |
| 242 | "token_uri": self.token_uri, |
| 243 | "client_id": self.client_id, |
| 244 | "client_secret": self.client_secret, |
| 245 | "scopes": self.scopes, |
| 246 | } |
| 247 | |
| 248 | # Remove empty entries |
| 249 | prep = {k: v for k, v in prep.items() if v is not None} |
| 250 | |
| 251 | # Remove entries that explicitely need to be removed |
| 252 | if strip is not None: |
| 253 | prep = {k: v for k, v in prep.items() if k not in strip} |
| 254 | |
| 255 | return json.dumps(prep) |