blob: 8e2a7f80593f3af2f9a06b4f2403924924d1cbce [file] [log] [blame]
Jon Wayne Parrott10ec7e92016-10-17 10:46:38 -07001# 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
17This module provides credentials based on OAuth 2.0 access and refresh tokens.
18These credentials usually access resources on behalf of a user (resource
19owner).
20
21Specifically, this is intended to use access tokens acquired using the
22`Authorization Code grant`_ and can refresh those tokens using a
23optional `refresh token`_.
24
25Obtaining the initial access and refresh token is outside of the scope of this
26module. Consult `rfc6749 section 4.1`_ for complete details on the
27Authorization 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 Jayathilaka23c88f72017-12-05 09:29:59 -080034import io
35import json
36
37import six
38
Jon Wayne Parrott10ec7e92016-10-17 10:46:38 -070039from google.auth import _helpers
40from google.auth import credentials
Thea Flowers118c0482018-05-24 13:34:07 -070041from google.auth import exceptions
Jon Wayne Parrott10ec7e92016-10-17 10:46:38 -070042from google.oauth2 import _client
43
44
Hiranya Jayathilaka23c88f72017-12-05 09:29:59 -080045# The Google OAuth 2.0 token endpoint. Used for authorized user credentials.
46_GOOGLE_OAUTH2_TOKEN_ENDPOINT = 'https://accounts.google.com/o/oauth2/token'
47
48
Mahmoud Bassiounycb7b3c42017-09-20 09:01:28 -070049class Credentials(credentials.ReadOnlyScoped, credentials.Credentials):
Jon Wayne Parrott10ec7e92016-10-17 10:46:38 -070050 """Credentials using OAuth 2.0 access and refresh tokens."""
51
Jon Wayne Parrott26a16372017-03-28 13:03:33 -070052 def __init__(self, token, refresh_token=None, id_token=None,
53 token_uri=None, client_id=None, client_secret=None,
54 scopes=None):
Jon Wayne Parrott10ec7e92016-10-17 10:46:38 -070055 """
56 Args:
57 token (Optional(str)): The OAuth 2.0 access token. Can be None
58 if refresh information is provided.
59 refresh_token (str): The OAuth 2.0 refresh token. If specified,
60 credentials can be refreshed.
Jon Wayne Parrott26a16372017-03-28 13:03:33 -070061 id_token (str): The Open ID Connect ID Token.
Jon Wayne Parrott10ec7e92016-10-17 10:46:38 -070062 token_uri (str): The OAuth 2.0 authorization server's token
63 endpoint URI. Must be specified for refresh, can be left as
64 None if the token can not be refreshed.
65 client_id (str): The OAuth 2.0 client ID. Must be specified for
66 refresh, can be left as None if the token can not be refreshed.
67 client_secret(str): The OAuth 2.0 client secret. Must be specified
68 for refresh, can be left as None if the token can not be
69 refreshed.
70 scopes (Sequence[str]): The scopes that were originally used
71 to obtain authorization. This is a purely informative parameter
72 that can be used by :meth:`has_scopes`. OAuth 2.0 credentials
73 can not request additional scopes after authorization.
74 """
75 super(Credentials, self).__init__()
76 self.token = token
77 self._refresh_token = refresh_token
Jon Wayne Parrott26a16372017-03-28 13:03:33 -070078 self._id_token = id_token
Jon Wayne Parrott10ec7e92016-10-17 10:46:38 -070079 self._scopes = scopes
80 self._token_uri = token_uri
81 self._client_id = client_id
82 self._client_secret = client_secret
83
84 @property
Jon Wayne Parrott2d0549a2017-03-01 09:27:16 -080085 def refresh_token(self):
86 """Optional[str]: The OAuth 2.0 refresh token."""
87 return self._refresh_token
88
89 @property
90 def token_uri(self):
91 """Optional[str]: The OAuth 2.0 authorization server's token endpoint
92 URI."""
93 return self._token_uri
94
95 @property
Jon Wayne Parrott26a16372017-03-28 13:03:33 -070096 def id_token(self):
97 """Optional[str]: The Open ID Connect ID Token.
98
99 Depending on the authorization server and the scopes requested, this
100 may be populated when credentials are obtained and updated when
101 :meth:`refresh` is called. This token is a JWT. It can be verified
102 and decoded using :func:`google.oauth2.id_token.verify_oauth2_token`.
103 """
104 return self._id_token
105
106 @property
Jon Wayne Parrott2d0549a2017-03-01 09:27:16 -0800107 def client_id(self):
108 """Optional[str]: The OAuth 2.0 client ID."""
109 return self._client_id
110
111 @property
112 def client_secret(self):
113 """Optional[str]: The OAuth 2.0 client secret."""
114 return self._client_secret
115
116 @property
Jon Wayne Parrott10ec7e92016-10-17 10:46:38 -0700117 def requires_scopes(self):
118 """False: OAuth 2.0 credentials have their scopes set when
119 the initial token is requested and can not be changed."""
120 return False
121
Jon Wayne Parrott10ec7e92016-10-17 10:46:38 -0700122 @_helpers.copy_docstring(credentials.Credentials)
123 def refresh(self, request):
Thea Flowers118c0482018-05-24 13:34:07 -0700124 if (self._refresh_token is None or
125 self._token_uri is None or
126 self._client_id is None or
127 self._client_secret is None):
128 raise exceptions.RefreshError(
129 'The credentials do not contain the necessary fields need to '
130 'refresh the access token. You must specify refresh_token, '
131 'token_uri, client_id, and client_secret.')
132
Jon Wayne Parrott26a16372017-03-28 13:03:33 -0700133 access_token, refresh_token, expiry, grant_response = (
134 _client.refresh_grant(
135 request, self._token_uri, self._refresh_token, self._client_id,
136 self._client_secret))
Jon Wayne Parrott10ec7e92016-10-17 10:46:38 -0700137
138 self.token = access_token
139 self.expiry = expiry
140 self._refresh_token = refresh_token
Jon Wayne Parrott26a16372017-03-28 13:03:33 -0700141 self._id_token = grant_response.get('id_token')
Hiranya Jayathilaka23c88f72017-12-05 09:29:59 -0800142
143 @classmethod
144 def from_authorized_user_info(cls, info, scopes=None):
145 """Creates a Credentials instance from parsed authorized user info.
146
147 Args:
148 info (Mapping[str, str]): The authorized user info in Google
149 format.
150 scopes (Sequence[str]): Optional list of scopes to include in the
151 credentials.
152
153 Returns:
154 google.oauth2.credentials.Credentials: The constructed
155 credentials.
156
157 Raises:
158 ValueError: If the info is not in the expected format.
159 """
160 keys_needed = set(('refresh_token', 'client_id', 'client_secret'))
161 missing = keys_needed.difference(six.iterkeys(info))
162
163 if missing:
164 raise ValueError(
165 'Authorized user info was not in the expected format, missing '
166 'fields {}.'.format(', '.join(missing)))
167
168 return Credentials(
169 None, # No access token, must be refreshed.
170 refresh_token=info['refresh_token'],
171 token_uri=_GOOGLE_OAUTH2_TOKEN_ENDPOINT,
172 scopes=scopes,
173 client_id=info['client_id'],
174 client_secret=info['client_secret'])
175
176 @classmethod
177 def from_authorized_user_file(cls, filename, scopes=None):
178 """Creates a Credentials instance from an authorized user json file.
179
180 Args:
181 filename (str): The path to the authorized user json file.
182 scopes (Sequence[str]): Optional list of scopes to include in the
183 credentials.
184
185 Returns:
186 google.oauth2.credentials.Credentials: The constructed
187 credentials.
188
189 Raises:
190 ValueError: If the file is not in the expected format.
191 """
192 with io.open(filename, 'r', encoding='utf-8') as json_file:
193 data = json.load(json_file)
194 return cls.from_authorized_user_info(data, scopes)