blob: 58580e2188a0190a5da30a5a3e39c14aa64fbed9 [file] [log] [blame]
Jon Wayne Parrottab9eba32016-10-17 10:49:57 -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"""Service Accounts: JSON Web Token (JWT) Profile for OAuth 2.0
16
17This module implements the JWT Profile for OAuth 2.0 Authorization Grants
18as defined by `RFC 7523`_ with particular support for how this RFC is
19implemented in Google's infrastructure. Google refers to these credentials
20as *Service Accounts*.
21
22Service accounts are used for server-to-server communication, such as
23interactions between a web application server and a Google service. The
24service account belongs to your application instead of to an individual end
25user. In contrast to other OAuth 2.0 profiles, no users are involved and your
26application "acts" as the service account.
27
28Typically an application uses a service account when the application uses
29Google APIs to work with its own data rather than a user's data. For example,
30an application that uses Google Cloud Datastore for data persistence would use
31a service account to authenticate its calls to the Google Cloud Datastore API.
32However, an application that needs to access a user's Drive documents would
33use the normal OAuth 2.0 profile.
34
35Additionally, Google Apps domain administrators can grant service accounts
36`domain-wide delegation`_ authority to access user data on behalf of users in
37the domain.
38
39This profile uses a JWT to acquire an OAuth 2.0 access token. The JWT is used
40in place of the usual authorization token returned during the standard
41OAuth 2.0 Authorization Code grant. The JWT is only used for this purpose, as
42the acquired access token is used as the bearer token when making requests
43using these credentials.
44
45This profile differs from normal OAuth 2.0 profile because no user consent
46step is required. The use of the private key allows this profile to assert
47identity directly.
48
49This profile also differs from the :mod:`google.auth.jwt` authentication
50because the JWT credentials use the JWT directly as the bearer token. This
51profile instead only uses the JWT to obtain an OAuth 2.0 access token. The
52obtained OAuth 2.0 access token is used as the bearer token.
53
54Domain-wide delegation
55----------------------
56
57Domain-wide delegation allows a service account to access user data on
58behalf of any user in a Google Apps domain without consent from the user.
59For example, an application that uses the Google Calendar API to add events to
60the calendars of all users in a Google Apps domain would use a service account
61to access the Google Calendar API on behalf of users.
62
63The Google Apps administrator must explicitly authorize the service account to
64do this. This authorization step is referred to as "delegating domain-wide
65authority" to a service account.
66
67You can use domain-wise delegation by creating a set of credentials with a
68specific subject using :meth:`~Credentials.with_subject`.
69
70.. _RFC 7523: https://tools.ietf.org/html/rfc7523
71"""
72
73import datetime
Jon Wayne Parrottab9eba32016-10-17 10:49:57 -070074
75from google.auth import _helpers
Jon Wayne Parrott807032c2016-10-18 09:38:26 -070076from google.auth import _service_account_info
Jon Wayne Parrottab9eba32016-10-17 10:49:57 -070077from google.auth import credentials
Jon Wayne Parrottab9eba32016-10-17 10:49:57 -070078from google.auth import jwt
79from google.oauth2 import _client
80
81_DEFAULT_TOKEN_LIFETIME_SECS = 3600 # 1 hour in sections
82
83
84class Credentials(credentials.Signing,
85 credentials.Scoped,
86 credentials.Credentials):
87 """Service account credentials
88
89 Usually, you'll create these credentials with one of the helper
90 constructors. To create credentials using a Google service account
91 private key JSON file::
92
93 credentials = service_account.Credentials.from_service_account_file(
94 'service-account.json')
95
96 Or if you already have the service account file loaded::
97
98 service_account_info = json.load(open('service_account.json'))
99 credentials = service_account.Credentials.from_service_account_info(
100 service_account_info)
101
102 Both helper methods pass on arguments to the constructor, so you can
103 specify additional scopes and a subject if necessary::
104
105 credentials = service_account.Credentials.from_service_account_file(
106 'service-account.json',
107 scopes=['email'],
108 subject='user@example.com')
109
110 The credentials are considered immutable. If you want to modify the scopes
111 or the subject used for delegation, use :meth:`with_scopes` or
112 :meth:`with_subject`::
113
114 scoped_credentials = credentials.with_scopes(['email'])
115 delegated_credentials = credentials.with_subject(subject)
116 """
117
118 def __init__(self, signer, service_account_email, token_uri, scopes=None,
119 subject=None, additional_claims=None):
120 """
121 Args:
122 signer (google.auth.crypt.Signer): The signer used to sign JWTs.
123 service_account_email (str): The service account's email.
124 scopes (Sequence[str]): Scopes to request during the authorization
125 grant.
126 token_uri (str): The OAuth 2.0 Token URI.
127 subject (str): For domain-wide delegation, the email address of the
128 user to for which to request delegated access.
129 additional_claims (Mapping[str, str]): Any additional claims for
130 the JWT assertion used in the authorization grant.
131
132 .. note:: Typically one of the helper constructors
133 :meth:`from_service_account_file` or
134 :meth:`from_service_account_info` are used instead of calling the
135 constructor directly.
136 """
137 super(Credentials, self).__init__()
138
139 self._scopes = scopes
140 self._signer = signer
141 self._service_account_email = service_account_email
142 self._subject = subject
143 self._token_uri = token_uri
144
145 if additional_claims is not None:
146 self._additional_claims = additional_claims
147 else:
148 self._additional_claims = {}
149
150 @classmethod
Jon Wayne Parrott807032c2016-10-18 09:38:26 -0700151 def _from_signer_and_info(cls, signer, info, **kwargs):
152 """Creates a Credentials instance from a signer and service account
153 info.
154
155 Args:
156 signer (google.auth.crypt.Signer): The signer used to sign JWTs.
157 info (Mapping[str, str]): The service account info.
158 kwargs: Additional arguments to pass to the constructor.
159
160 Returns:
161 google.auth.jwt.Credentials: The constructed credentials.
162
163 Raises:
164 ValueError: If the info is not in the expected format.
165 """
166 return cls(
167 signer,
168 service_account_email=info['client_email'],
169 token_uri=info['token_uri'], **kwargs)
170
171 @classmethod
Jon Wayne Parrottab9eba32016-10-17 10:49:57 -0700172 def from_service_account_info(cls, info, **kwargs):
173 """Creates a Credentials instance from parsed service account info.
174
175 Args:
176 info (Mapping[str, str]): The service account info in Google
177 format.
178 kwargs: Additional arguments to pass to the constructor.
179
180 Returns:
181 google.auth.service_account.Credentials: The constructed
182 credentials.
183
184 Raises:
185 ValueError: If the info is not in the expected format.
186 """
Jon Wayne Parrott807032c2016-10-18 09:38:26 -0700187 signer = _service_account_info.from_dict(
188 info, require=['client_email', 'token_uri'])
189 return cls._from_signer_and_info(signer, info, **kwargs)
Jon Wayne Parrottab9eba32016-10-17 10:49:57 -0700190
191 @classmethod
192 def from_service_account_file(cls, filename, **kwargs):
193 """Creates a Credentials instance from a service account json file.
194
195 Args:
196 filename (str): The path to the service account json file.
197 kwargs: Additional arguments to pass to the constructor.
198
199 Returns:
200 google.auth.service_account.Credentials: The constructed
201 credentials.
202 """
Jon Wayne Parrott807032c2016-10-18 09:38:26 -0700203 info, signer = _service_account_info.from_filename(
204 filename, require=['client_email', 'token_uri'])
205 return cls._from_signer_and_info(signer, info, **kwargs)
Jon Wayne Parrottab9eba32016-10-17 10:49:57 -0700206
Jon Wayne Parrottab9eba32016-10-17 10:49:57 -0700207 @property
Jon Wayne Parrott61ffb052016-11-08 09:30:30 -0800208 def service_account_email(self):
209 """The service account email."""
210 return self._service_account_email
211
212 @property
Jon Wayne Parrottab9eba32016-10-17 10:49:57 -0700213 def requires_scopes(self):
214 """Checks if the credentials requires scopes.
215
216 Returns:
217 bool: True if there are no scopes set otherwise False.
218 """
219 return True if not self._scopes else False
220
221 @_helpers.copy_docstring(credentials.Scoped)
222 def with_scopes(self, scopes):
223 return Credentials(
224 self._signer,
225 service_account_email=self._service_account_email,
226 scopes=scopes,
227 token_uri=self._token_uri,
228 subject=self._subject,
229 additional_claims=self._additional_claims.copy())
230
231 def with_subject(self, subject):
232 """Create a copy of these credentials with the specified subject.
233
234 Args:
235 subject (str): The subject claim.
236
237 Returns:
238 google.auth.service_account.Credentials: A new credentials
239 instance.
240 """
241 return Credentials(
242 self._signer,
243 service_account_email=self._service_account_email,
244 scopes=self._scopes,
245 token_uri=self._token_uri,
246 subject=subject,
247 additional_claims=self._additional_claims.copy())
248
249 def _make_authorization_grant_assertion(self):
250 """Create the OAuth 2.0 assertion.
251
252 This assertion is used during the OAuth 2.0 grant to acquire an
253 access token.
254
255 Returns:
256 bytes: The authorization grant assertion.
257 """
258 now = _helpers.utcnow()
259 lifetime = datetime.timedelta(seconds=_DEFAULT_TOKEN_LIFETIME_SECS)
260 expiry = now + lifetime
261
262 payload = {
263 'iat': _helpers.datetime_to_secs(now),
264 'exp': _helpers.datetime_to_secs(expiry),
265 # The issuer must be the service account email.
266 'iss': self._service_account_email,
267 # The audience must be the auth token endpoint's URI
268 'aud': self._token_uri,
269 'scope': _helpers.scopes_to_string(self._scopes or ())
270 }
271
272 payload.update(self._additional_claims)
273
274 # The subject can be a user email for domain-wide delegation.
275 if self._subject:
276 payload.setdefault('sub', self._subject)
277
278 token = jwt.encode(self._signer, payload)
279
280 return token
281
282 @_helpers.copy_docstring(credentials.Credentials)
283 def refresh(self, request):
284 assertion = self._make_authorization_grant_assertion()
285 access_token, expiry, _ = _client.jwt_grant(
286 request, self._token_uri, assertion)
287 self.token = access_token
288 self.expiry = expiry
289
290 @_helpers.copy_docstring(credentials.Signing)
291 def sign_bytes(self, message):
292 return self._signer.sign(message)
Jon Wayne Parrott4c883f02016-12-02 14:26:33 -0800293
294 @property
295 @_helpers.copy_docstring(credentials.Signing)
Jon Wayne Parrottd7221672017-02-16 09:05:11 -0800296 def signer(self):
297 return self._signer
298
299 @property
300 @_helpers.copy_docstring(credentials.Signing)
Jon Wayne Parrott4c883f02016-12-02 14:26:33 -0800301 def signer_email(self):
302 return self._service_account_email