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 |
| 41 | from google.oauth2 import _client |
| 42 | |
| 43 | |
Hiranya Jayathilaka | 23c88f7 | 2017-12-05 09:29:59 -0800 | [diff] [blame] | 44 | # The Google OAuth 2.0 token endpoint. Used for authorized user credentials. |
| 45 | _GOOGLE_OAUTH2_TOKEN_ENDPOINT = 'https://accounts.google.com/o/oauth2/token' |
| 46 | |
| 47 | |
Mahmoud Bassiouny | cb7b3c4 | 2017-09-20 09:01:28 -0700 | [diff] [blame] | 48 | class Credentials(credentials.ReadOnlyScoped, credentials.Credentials): |
Jon Wayne Parrott | 10ec7e9 | 2016-10-17 10:46:38 -0700 | [diff] [blame] | 49 | """Credentials using OAuth 2.0 access and refresh tokens.""" |
| 50 | |
Jon Wayne Parrott | 26a1637 | 2017-03-28 13:03:33 -0700 | [diff] [blame] | 51 | def __init__(self, token, refresh_token=None, id_token=None, |
| 52 | token_uri=None, client_id=None, client_secret=None, |
| 53 | scopes=None): |
Jon Wayne Parrott | 10ec7e9 | 2016-10-17 10:46:38 -0700 | [diff] [blame] | 54 | """ |
| 55 | Args: |
| 56 | token (Optional(str)): The OAuth 2.0 access token. Can be None |
| 57 | if refresh information is provided. |
| 58 | refresh_token (str): The OAuth 2.0 refresh token. If specified, |
| 59 | credentials can be refreshed. |
Jon Wayne Parrott | 26a1637 | 2017-03-28 13:03:33 -0700 | [diff] [blame] | 60 | id_token (str): The Open ID Connect ID Token. |
Jon Wayne Parrott | 10ec7e9 | 2016-10-17 10:46:38 -0700 | [diff] [blame] | 61 | token_uri (str): The OAuth 2.0 authorization server's token |
| 62 | endpoint URI. Must be specified for refresh, can be left as |
| 63 | None if the token can not be refreshed. |
| 64 | client_id (str): The OAuth 2.0 client ID. Must be specified for |
| 65 | refresh, can be left as None if the token can not be refreshed. |
| 66 | client_secret(str): The OAuth 2.0 client secret. Must be specified |
| 67 | for refresh, can be left as None if the token can not be |
| 68 | refreshed. |
| 69 | scopes (Sequence[str]): The scopes that were originally used |
| 70 | to obtain authorization. This is a purely informative parameter |
| 71 | that can be used by :meth:`has_scopes`. OAuth 2.0 credentials |
| 72 | can not request additional scopes after authorization. |
| 73 | """ |
| 74 | super(Credentials, self).__init__() |
| 75 | self.token = token |
| 76 | self._refresh_token = refresh_token |
Jon Wayne Parrott | 26a1637 | 2017-03-28 13:03:33 -0700 | [diff] [blame] | 77 | self._id_token = id_token |
Jon Wayne Parrott | 10ec7e9 | 2016-10-17 10:46:38 -0700 | [diff] [blame] | 78 | self._scopes = scopes |
| 79 | self._token_uri = token_uri |
| 80 | self._client_id = client_id |
| 81 | self._client_secret = client_secret |
| 82 | |
| 83 | @property |
Jon Wayne Parrott | 2d0549a | 2017-03-01 09:27:16 -0800 | [diff] [blame] | 84 | def refresh_token(self): |
| 85 | """Optional[str]: The OAuth 2.0 refresh token.""" |
| 86 | return self._refresh_token |
| 87 | |
| 88 | @property |
| 89 | def token_uri(self): |
| 90 | """Optional[str]: The OAuth 2.0 authorization server's token endpoint |
| 91 | URI.""" |
| 92 | return self._token_uri |
| 93 | |
| 94 | @property |
Jon Wayne Parrott | 26a1637 | 2017-03-28 13:03:33 -0700 | [diff] [blame] | 95 | def id_token(self): |
| 96 | """Optional[str]: The Open ID Connect ID Token. |
| 97 | |
| 98 | Depending on the authorization server and the scopes requested, this |
| 99 | may be populated when credentials are obtained and updated when |
| 100 | :meth:`refresh` is called. This token is a JWT. It can be verified |
| 101 | and decoded using :func:`google.oauth2.id_token.verify_oauth2_token`. |
| 102 | """ |
| 103 | return self._id_token |
| 104 | |
| 105 | @property |
Jon Wayne Parrott | 2d0549a | 2017-03-01 09:27:16 -0800 | [diff] [blame] | 106 | def client_id(self): |
| 107 | """Optional[str]: The OAuth 2.0 client ID.""" |
| 108 | return self._client_id |
| 109 | |
| 110 | @property |
| 111 | def client_secret(self): |
| 112 | """Optional[str]: The OAuth 2.0 client secret.""" |
| 113 | return self._client_secret |
| 114 | |
| 115 | @property |
Jon Wayne Parrott | 10ec7e9 | 2016-10-17 10:46:38 -0700 | [diff] [blame] | 116 | def requires_scopes(self): |
| 117 | """False: OAuth 2.0 credentials have their scopes set when |
| 118 | the initial token is requested and can not be changed.""" |
| 119 | return False |
| 120 | |
Jon Wayne Parrott | 10ec7e9 | 2016-10-17 10:46:38 -0700 | [diff] [blame] | 121 | @_helpers.copy_docstring(credentials.Credentials) |
| 122 | def refresh(self, request): |
Jon Wayne Parrott | 26a1637 | 2017-03-28 13:03:33 -0700 | [diff] [blame] | 123 | access_token, refresh_token, expiry, grant_response = ( |
| 124 | _client.refresh_grant( |
| 125 | request, self._token_uri, self._refresh_token, self._client_id, |
| 126 | self._client_secret)) |
Jon Wayne Parrott | 10ec7e9 | 2016-10-17 10:46:38 -0700 | [diff] [blame] | 127 | |
| 128 | self.token = access_token |
| 129 | self.expiry = expiry |
| 130 | self._refresh_token = refresh_token |
Jon Wayne Parrott | 26a1637 | 2017-03-28 13:03:33 -0700 | [diff] [blame] | 131 | self._id_token = grant_response.get('id_token') |
Hiranya Jayathilaka | 23c88f7 | 2017-12-05 09:29:59 -0800 | [diff] [blame] | 132 | |
| 133 | @classmethod |
| 134 | def from_authorized_user_info(cls, info, scopes=None): |
| 135 | """Creates a Credentials instance from parsed authorized user info. |
| 136 | |
| 137 | Args: |
| 138 | info (Mapping[str, str]): The authorized user info in Google |
| 139 | format. |
| 140 | scopes (Sequence[str]): Optional list of scopes to include in the |
| 141 | credentials. |
| 142 | |
| 143 | Returns: |
| 144 | google.oauth2.credentials.Credentials: The constructed |
| 145 | credentials. |
| 146 | |
| 147 | Raises: |
| 148 | ValueError: If the info is not in the expected format. |
| 149 | """ |
| 150 | keys_needed = set(('refresh_token', 'client_id', 'client_secret')) |
| 151 | missing = keys_needed.difference(six.iterkeys(info)) |
| 152 | |
| 153 | if missing: |
| 154 | raise ValueError( |
| 155 | 'Authorized user info was not in the expected format, missing ' |
| 156 | 'fields {}.'.format(', '.join(missing))) |
| 157 | |
| 158 | return Credentials( |
| 159 | None, # No access token, must be refreshed. |
| 160 | refresh_token=info['refresh_token'], |
| 161 | token_uri=_GOOGLE_OAUTH2_TOKEN_ENDPOINT, |
| 162 | scopes=scopes, |
| 163 | client_id=info['client_id'], |
| 164 | client_secret=info['client_secret']) |
| 165 | |
| 166 | @classmethod |
| 167 | def from_authorized_user_file(cls, filename, scopes=None): |
| 168 | """Creates a Credentials instance from an authorized user json file. |
| 169 | |
| 170 | Args: |
| 171 | filename (str): The path to the authorized user json file. |
| 172 | scopes (Sequence[str]): Optional list of scopes to include in the |
| 173 | credentials. |
| 174 | |
| 175 | Returns: |
| 176 | google.oauth2.credentials.Credentials: The constructed |
| 177 | credentials. |
| 178 | |
| 179 | Raises: |
| 180 | ValueError: If the file is not in the expected format. |
| 181 | """ |
| 182 | with io.open(filename, 'r', encoding='utf-8') as json_file: |
| 183 | data = json.load(json_file) |
| 184 | return cls.from_authorized_user_info(data, scopes) |