forked from firebase/firebase-admin-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.py
More file actions
855 lines (680 loc) · 30.8 KB
/
auth.py
File metadata and controls
855 lines (680 loc) · 30.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Firebase Authentication module.
This module contains functions for minting and verifying JWTs used for
authenticating against Firebase services. It also provides functions for
creating and managing user accounts in Firebase projects.
"""
import json
import time
from google.auth import jwt
from google.auth import transport
import google.oauth2.id_token
import six
from firebase_admin import credentials
from firebase_admin import _user_mgt
from firebase_admin import _utils
# Provided for overriding during tests.
_request = transport.requests.Request()
_AUTH_ATTRIBUTE = '_auth'
_ID_TOKEN_REVOKED = 'ID_TOKEN_REVOKED'
def _get_auth_service(app):
"""Returns an _AuthService instance for an App.
If the App already has an _AuthService associated with it, simply returns
it. Otherwise creates a new _AuthService, and adds it to the App before
returning it.
Args:
app: A Firebase App instance (or None to use the default App).
Returns:
_AuthService: An _AuthService for the specified App instance.
Raises:
ValueError: If the app argument is invalid.
"""
return _utils.get_app_service(app, _AUTH_ATTRIBUTE, _AuthService)
def create_custom_token(uid, developer_claims=None, app=None):
"""Builds and signs a Firebase custom auth token.
Args:
uid: ID of the user for whom the token is created.
developer_claims: A dictionary of claims to be included in the token
(optional).
app: An App instance (optional).
Returns:
string: A token minted from the input parameters.
Raises:
ValueError: If input parameters are invalid.
"""
token_generator = _get_auth_service(app).token_generator
return token_generator.create_custom_token(uid, developer_claims)
def verify_id_token(id_token, app=None, check_revoked=False):
"""Verifies the signature and data for the provided JWT.
Accepts a signed token string, verifies that it is current, and issued
to this project, and that it was correctly signed by Google.
Args:
id_token: A string of the encoded JWT.
app: An App instance (optional).
check_revoked: Boolean, If true, checks whether the token has been revoked (optional).
Returns:
dict: A dictionary of key-value pairs parsed from the decoded JWT.
Raises:
ValueError: If the JWT was found to be invalid, or if the App was not
initialized with a credentials.Certificate.
AuthError: If check_revoked is requested and the token was revoked.
"""
if not isinstance(check_revoked, bool):
# guard against accidental wrong assignment.
raise ValueError('Illegal check_revoked argument. Argument must be of type '
' bool, but given "{0}".'.format(type(app)))
token_generator = _get_auth_service(app).token_generator
verified_claims = token_generator.verify_id_token(id_token)
if check_revoked:
user = get_user(verified_claims.get('uid'), app)
if verified_claims.get('iat') * 1000 < user.tokens_valid_after_timestamp:
raise AuthError(_ID_TOKEN_REVOKED, 'The Firebase ID token has been revoked.')
return verified_claims
def revoke_refresh_tokens(uid, app=None):
"""Revokes all refresh tokens for an existing user.
revoke_refresh_tokens updates the user's tokens_valid_after_timestamp to the current UTC
in seconds since the epoch. It is important that the server on which this is called has its
clock set correctly and synchronized.
While this revokes all sessions for a specified user and disables any new ID tokens for
existing sessions from getting minted, existing ID tokens may remain active until their
natural expiration (one hour). To verify that ID tokens are revoked, use
`verify_id_token(idToken, check_revoked=True)`.
"""
user_manager = _get_auth_service(app).user_manager
user_manager.update_user(uid, valid_since=int(time.time()))
def get_user(uid, app=None):
"""Gets the user data corresponding to the specified user ID.
Args:
uid: A user ID string.
app: An App instance (optional).
Returns:
UserRecord: A UserRecord instance.
Raises:
ValueError: If the user ID is None, empty or malformed.
AuthError: If an error occurs while retrieving the user or if the specified user ID
does not exist.
"""
user_manager = _get_auth_service(app).user_manager
try:
response = user_manager.get_user(uid=uid)
return UserRecord(response)
except _user_mgt.ApiCallError as error:
raise AuthError(error.code, str(error), error.detail)
def get_user_by_email(email, app=None):
"""Gets the user data corresponding to the specified user email.
Args:
email: A user email address string.
app: An App instance (optional).
Returns:
UserRecord: A UserRecord instance.
Raises:
ValueError: If the email is None, empty or malformed.
AuthError: If an error occurs while retrieving the user or no user exists by the specified
email address.
"""
user_manager = _get_auth_service(app).user_manager
try:
response = user_manager.get_user(email=email)
return UserRecord(response)
except _user_mgt.ApiCallError as error:
raise AuthError(error.code, str(error), error.detail)
def get_user_by_phone_number(phone_number, app=None):
"""Gets the user data corresponding to the specified phone number.
Args:
phone_number: A phone number string.
app: An App instance (optional).
Returns:
UserRecord: A UserRecord instance.
Raises:
ValueError: If the phone number is None, empty or malformed.
AuthError: If an error occurs while retrieving the user or no user exists by the specified
phone number.
"""
user_manager = _get_auth_service(app).user_manager
try:
response = user_manager.get_user(phone_number=phone_number)
return UserRecord(response)
except _user_mgt.ApiCallError as error:
raise AuthError(error.code, str(error), error.detail)
def list_users(page_token=None, max_results=_user_mgt.MAX_LIST_USERS_RESULTS, app=None):
"""Retrieves a page of user accounts from a Firebase project.
The ``page_token`` argument governs the starting point of the page. The ``max_results``
argument governs the maximum number of user accounts that may be included in the returned page.
This function never returns None. If there are no user accounts in the Firebase project, this
returns an empty page.
Args:
page_token: A non-empty page token string, which indicates the starting point of the page
(optional). Defaults to ``None``, which will retrieve the first page of users.
max_results: A positive integer indicating the maximum number of users to include in the
returned page (optional). Defaults to 1000, which is also the maximum number allowed.
app: An App instance (optional).
Returns:
ListUsersPage: A ListUsersPage instance.
Raises:
ValueError: If max_results or page_token are invalid.
AuthError: If an error occurs while retrieving the user accounts.
"""
user_manager = _get_auth_service(app).user_manager
def download(page_token, max_results):
try:
return user_manager.list_users(page_token, max_results)
except _user_mgt.ApiCallError as error:
raise AuthError(error.code, str(error), error.detail)
return ListUsersPage(download, page_token, max_results)
def create_user(**kwargs):
"""Creates a new user account with the specified properties.
Keyword Args:
uid: User ID to assign to the newly created user (optional).
display_name: The user's display name (optional).
email: The user's primary email (optional).
email_verified: A boolean indicating whether or not the user's primary email is
verified (optional).
phone_number: The user's primary phone number (optional).
photo_url: The user's photo URL (optional).
password: The user's raw, unhashed password. (optional).
disabled: A boolean indicating whether or not the user account is disabled (optional).
app: An App instance (optional).
Returns:
UserRecord: A UserRecord instance for the newly created user.
Raises:
ValueError: If the specified user properties are invalid.
AuthError: If an error occurs while creating the user account.
"""
app = kwargs.pop('app', None)
user_manager = _get_auth_service(app).user_manager
try:
uid = user_manager.create_user(**kwargs)
return UserRecord(user_manager.get_user(uid=uid))
except _user_mgt.ApiCallError as error:
raise AuthError(error.code, str(error), error.detail)
def update_user(uid, **kwargs):
"""Updates an existing user account with the specified properties.
Args:
uid: A user ID string.
kwargs: A series of keyword arguments (optional).
Keyword Args:
display_name: The user's display name (optional). Can be removed by explicitly passing
None.
email: The user's primary email (optional).
email_verified: A boolean indicating whether or not the user's primary email is
verified (optional).
phone_number: The user's primary phone number (optional). Can be removed by explicitly
passing None.
photo_url: The user's photo URL (optional). Can be removed by explicitly passing None.
password: The user's raw, unhashed password. (optional).
disabled: A boolean indicating whether or not the user account is disabled (optional).
custom_claims: A dictionary or a JSON string contining the custom claims to be set on the
user account (optional).
valid_since: An integer signifying the seconds since the epoch. This field is set by
`revoke_refresh_tokens` and it is discouraged to set this field directly.
Returns:
UserRecord: An updated UserRecord instance for the user.
Raises:
ValueError: If the specified user ID or properties are invalid.
AuthError: If an error occurs while updating the user account.
"""
app = kwargs.pop('app', None)
user_manager = _get_auth_service(app).user_manager
try:
user_manager.update_user(uid, **kwargs)
return UserRecord(user_manager.get_user(uid=uid))
except _user_mgt.ApiCallError as error:
raise AuthError(error.code, str(error), error.detail)
def set_custom_user_claims(uid, custom_claims, app=None):
"""Sets additional claims on an existing user account.
Custom claims set via this function can be used to define user roles and privilege levels.
These claims propagate to all the devices where the user is already signed in (after token
expiration or when token refresh is forced), and next time the user signs in. The claims
can be accessed via the user's ID token JWT. If a reserved OIDC claim is specified (sub, iat,
iss, etc), an error is thrown. Claims payload must also not be larger then 1000 characters
when serialized into a JSON string.
Args:
uid: A user ID string.
custom_claims: A dictionary or a JSON string of custom claims. Pass None to unset any
claims set previously.
app: An App instance (optional).
Raises:
ValueError: If the specified user ID or the custom claims are invalid.
AuthError: If an error occurs while updating the user account.
"""
user_manager = _get_auth_service(app).user_manager
try:
user_manager.update_user(uid, custom_claims=custom_claims)
except _user_mgt.ApiCallError as error:
raise AuthError(error.code, str(error), error.detail)
def delete_user(uid, app=None):
"""Deletes the user identified by the specified user ID.
Args:
uid: A user ID string.
app: An App instance (optional).
Raises:
ValueError: If the user ID is None, empty or malformed.
AuthError: If an error occurs while deleting the user account.
"""
user_manager = _get_auth_service(app).user_manager
try:
user_manager.delete_user(uid)
except _user_mgt.ApiCallError as error:
raise AuthError(error.code, str(error), error.detail)
class UserInfo(object):
"""A collection of standard profile information for a user.
Used to expose profile information returned by an identity provider.
"""
@property
def uid(self):
"""Returns the user ID of this user."""
raise NotImplementedError
@property
def display_name(self):
"""Returns the display name of this user."""
raise NotImplementedError
@property
def email(self):
"""Returns the email address associated with this user."""
raise NotImplementedError
@property
def phone_number(self):
"""Returns the phone number associated with this user."""
raise NotImplementedError
@property
def photo_url(self):
"""Returns the photo URL of this user."""
raise NotImplementedError
@property
def provider_id(self):
"""Returns the ID of the identity provider.
This can be a short domain name (e.g. google.com), or the identity of an OpenID
identity provider.
"""
raise NotImplementedError
class UserRecord(UserInfo):
"""Contains metadata associated with a Firebase user account."""
def __init__(self, data):
super(UserRecord, self).__init__()
if not isinstance(data, dict):
raise ValueError('Invalid data argument: {0}. Must be a dictionary.'.format(data))
if not data.get('localId'):
raise ValueError('User ID must not be None or empty.')
self._data = data
@property
def uid(self):
"""Returns the user ID of this user.
Returns:
string: A user ID string. This value is never None or empty.
"""
return self._data.get('localId')
@property
def display_name(self):
"""Returns the display name of this user.
Returns:
string: A display name string or None.
"""
return self._data.get('displayName')
@property
def email(self):
"""Returns the email address associated with this user.
Returns:
string: An email address string or None.
"""
return self._data.get('email')
@property
def phone_number(self):
"""Returns the phone number associated with this user.
Returns:
string: A phone number string or None.
"""
return self._data.get('phoneNumber')
@property
def photo_url(self):
"""Returns the photo URL of this user.
Returns:
string: A URL string or None.
"""
return self._data.get('photoUrl')
@property
def provider_id(self):
"""Returns the provider ID of this user.
Returns:
string: A constant provider ID value.
"""
return 'firebase'
@property
def email_verified(self):
"""Returns whether the email address of this user has been verified.
Returns:
bool: True if the email has been verified, and False otherwise.
"""
return bool(self._data.get('emailVerified'))
@property
def disabled(self):
"""Returns whether this user account is disabled.
Returns:
bool: True if the user account is disabled, and False otherwise.
"""
return bool(self._data.get('disabled'))
@property
def tokens_valid_after_timestamp(self):
"""Returns the time, in milliseconds since the epoch, before which tokens are invalid.
Note: this is truncated to 1 second accuracy.
Returns:
int: Timestamp in milliseconds since the epoch, truncated to the second.
All tokens issued before that time are considered revoked.
"""
valid_since = self._data.get('validSince')
if valid_since is not None:
return 1000 * int(valid_since)
return None
@property
def user_metadata(self):
"""Returns additional metadata associated with this user.
Returns:
UserMetadata: A UserMetadata instance. Does not return None.
"""
return UserMetadata(self._data)
@property
def provider_data(self):
"""Returns a list of UserInfo instances.
Each object represents an identity from an identity provider that is linked to this user.
Returns:
list: A list of UserInfo objects, which may be empty.
"""
providers = self._data.get('providerUserInfo', [])
return [_ProviderUserInfo(entry) for entry in providers]
@property
def custom_claims(self):
"""Returns any custom claims set on this user account.
Returns:
dict: A dictionary of claims or None.
"""
claims = self._data.get('customAttributes')
if claims:
parsed = json.loads(claims)
if parsed != {}:
return parsed
return None
class UserMetadata(object):
"""Contains additional metadata associated with a user account."""
def __init__(self, data):
if not isinstance(data, dict):
raise ValueError('Invalid data argument: {0}. Must be a dictionary.'.format(data))
self._data = data
@property
def creation_timestamp(self):
""" Creation timestamp in milliseconds since the epoch.
Returns:
integer: The user creation timestamp in milliseconds since the epoch.
"""
if 'createdAt' in self._data:
return int(self._data['createdAt'])
return None
@property
def last_sign_in_timestamp(self):
""" Last sign in timestamp in milliseconds since the epoch.
Returns:
integer: The last sign in timestamp in milliseconds since the epoch.
"""
if 'lastLoginAt' in self._data:
return int(self._data['lastLoginAt'])
return None
class ExportedUserRecord(UserRecord):
"""Contains metadata associated with a user including password hash and salt."""
def __init__(self, data):
super(ExportedUserRecord, self).__init__(data)
@property
def password_hash(self):
"""The user's password hash as a base64-encoded string.
If the Firebase Auth hashing algorithm (SCRYPT) was used to create the user account, this
is the base64-encoded password hash of the user. If a different hashing algorithm was
used to create this user, as is typical when migrating from another Auth system, this
is an empty string. If no password is set, this is ``None``.
"""
return self._data.get('passwordHash')
@property
def password_salt(self):
"""The user's password salt as a base64-encoded string.
If the Firebase Auth hashing algorithm (SCRYPT) was used to create the user account, this
is the base64-encoded password salt of the user. If a different hashing algorithm was
used to create this user, as is typical when migrating from another Auth system, this is
an empty string. If no password is set, this is ``None``.
"""
return self._data.get('salt')
class ListUsersPage(object):
"""Represents a page of user records exported from a Firebase project.
Provides methods for traversing the user accounts included in this page, as well as retrieving
subsequent pages of users. The iterator returned by ``iterate_all()`` can be used to iterate
through all users in the Firebase project starting from this page.
"""
def __init__(self, download, page_token, max_results):
self._download = download
self._max_results = max_results
self._current = download(page_token, max_results)
@property
def users(self):
"""A list of ``ExportedUserRecord`` instances available in this page."""
return [ExportedUserRecord(user) for user in self._current.get('users', [])]
@property
def next_page_token(self):
"""Page token string for the next page (empty string indicates no more pages)."""
return self._current.get('nextPageToken', '')
@property
def has_next_page(self):
"""A boolean indicating whether more pages are available."""
return bool(self.next_page_token)
def get_next_page(self):
"""Retrieves the next page of user accounts, if available.
Returns:
ListUsersPage: Next page of users, or None if this is the last page.
"""
if self.has_next_page:
return ListUsersPage(self._download, self.next_page_token, self._max_results)
return None
def iterate_all(self):
"""Retrieves an iterator for user accounts.
Returned iterator will iterate through all the user accounts in the Firebase project
starting from this page. The iterator will never buffer more than one page of users
in memory at a time.
Returns:
iterator: An iterator of ExportedUserRecord instances.
"""
return _user_mgt.UserIterator(self)
class _ProviderUserInfo(UserInfo):
"""Contains metadata regarding how a user is known by a particular identity provider."""
def __init__(self, data):
super(_ProviderUserInfo, self).__init__()
if not isinstance(data, dict):
raise ValueError('Invalid data argument: {0}. Must be a dictionary.'.format(data))
if not data.get('rawId'):
raise ValueError('User ID must not be None or empty.')
self._data = data
@property
def uid(self):
return self._data.get('rawId')
@property
def display_name(self):
return self._data.get('displayName')
@property
def email(self):
return self._data.get('email')
@property
def phone_number(self):
return self._data.get('phoneNumber')
@property
def photo_url(self):
return self._data.get('photoUrl')
@property
def provider_id(self):
return self._data.get('providerId')
class AuthError(Exception):
"""Represents an Exception encountered while invoking the Firebase auth API."""
def __init__(self, code, message, error=None):
Exception.__init__(self, message)
self.code = code
self.detail = error
class _TokenGenerator(object):
"""Generates custom tokens, and validates ID tokens."""
FIREBASE_CERT_URI = ('https://www.googleapis.com/robot/v1/metadata/x509/'
'securetoken@system.gserviceaccount.com')
ISSUER_PREFIX = 'https://securetoken.google.com/'
MAX_TOKEN_LIFETIME_SECONDS = 3600 # One Hour, in Seconds
FIREBASE_AUDIENCE = ('https://identitytoolkit.googleapis.com/google.'
'identity.identitytoolkit.v1.IdentityToolkit')
# Key names we don't allow to appear in the developer_claims.
_RESERVED_CLAIMS_ = set([
'acr', 'amr', 'at_hash', 'aud', 'auth_time', 'azp', 'cnf', 'c_hash',
'exp', 'firebase', 'iat', 'iss', 'jti', 'nbf', 'nonce', 'sub'
])
def __init__(self, app):
"""Initializes FirebaseAuth from a FirebaseApp instance.
Args:
app: A FirebaseApp instance.
"""
self._app = app
def create_custom_token(self, uid, developer_claims=None):
"""Builds and signs a FirebaseCustomAuthToken.
Args:
uid: ID of the user for whom the token is created.
developer_claims: A dictionary of claims to be included in the token.
Returns:
string: A token minted from the input parameters as a byte string.
Raises:
ValueError: If input parameters are invalid.
"""
if not isinstance(self._app.credential, credentials.Certificate):
raise ValueError(
'Must initialize Firebase App with a certificate credential '
'to call create_custom_token().')
if developer_claims is not None:
if not isinstance(developer_claims, dict):
raise ValueError('developer_claims must be a dictionary')
disallowed_keys = set(developer_claims.keys()
) & self._RESERVED_CLAIMS_
if disallowed_keys:
if len(disallowed_keys) > 1:
error_message = ('Developer claims {0} are reserved and '
'cannot be specified.'.format(
', '.join(disallowed_keys)))
else:
error_message = ('Developer claim {0} is reserved and '
'cannot be specified.'.format(
', '.join(disallowed_keys)))
raise ValueError(error_message)
if not uid or not isinstance(uid, six.string_types) or len(uid) > 128:
raise ValueError('uid must be a string between 1 and 128 characters.')
now = int(time.time())
payload = {
'iss': self._app.credential.service_account_email,
'sub': self._app.credential.service_account_email,
'aud': self.FIREBASE_AUDIENCE,
'uid': uid,
'iat': now,
'exp': now + self.MAX_TOKEN_LIFETIME_SECONDS,
}
if developer_claims is not None:
payload['claims'] = developer_claims
return jwt.encode(self._app.credential.signer, payload)
def verify_id_token(self, id_token):
"""Verifies the signature and data for the provided JWT.
Accepts a signed token string, verifies that is the current, and issued
to this project, and that it was correctly signed by Google.
Args:
id_token: A string of the encoded JWT.
Returns:
dict: A dictionary of key-value pairs parsed from the decoded JWT.
Raises:
ValueError: The JWT was found to be invalid, or the app was not initialized with a
credentials.Certificate instance.
"""
if not id_token:
raise ValueError('Illegal ID token provided: {0}. ID token must be a non-empty '
'string.'.format(id_token))
if isinstance(id_token, six.text_type):
id_token = id_token.encode('ascii')
if not isinstance(id_token, six.binary_type):
raise ValueError('Illegal ID token provided: {0}. ID token must be a non-empty '
'string.'.format(id_token))
project_id = self._app.project_id
if not project_id:
raise ValueError('Failed to ascertain project ID from the credential or the '
'environment. Project ID is required to call verify_id_token(). '
'Initialize the app with a credentials.Certificate or set '
'your Firebase project ID as an app option. Alternatively '
'set the GCLOUD_PROJECT environment variable.')
header = jwt.decode_header(id_token)
payload = jwt.decode(id_token, verify=False)
issuer = payload.get('iss')
audience = payload.get('aud')
subject = payload.get('sub')
expected_issuer = self.ISSUER_PREFIX + project_id
project_id_match_msg = ('Make sure the ID token comes from the same'
' Firebase project as the service account used'
' to authenticate this SDK.')
verify_id_token_msg = (
'See https://firebase.google.com/docs/auth/admin/verify-id-tokens'
' for details on how to retrieve an ID token.')
error_message = None
if not header.get('kid'):
if audience == self.FIREBASE_AUDIENCE:
error_message = ('verify_id_token() expects an ID token, but '
'was given a custom token.')
elif header.get('alg') == 'HS256' and payload.get(
'v') is 0 and 'uid' in payload.get('d', {}):
error_message = ('verify_id_token() expects an ID token, but '
'was given a legacy custom token.')
else:
error_message = 'Firebase ID token has no "kid" claim.'
elif header.get('alg') != 'RS256':
error_message = ('Firebase ID token has incorrect algorithm. '
'Expected "RS256" but got "{0}". {1}'.format(
header.get('alg'), verify_id_token_msg))
elif audience != project_id:
error_message = (
'Firebase ID token has incorrect "aud" (audience) claim. '
'Expected "{0}" but got "{1}". {2} {3}'.format(
project_id, audience, project_id_match_msg,
verify_id_token_msg))
elif issuer != expected_issuer:
error_message = ('Firebase ID token has incorrect "iss" (issuer) '
'claim. Expected "{0}" but got "{1}". {2} {3}'
.format(expected_issuer, issuer,
project_id_match_msg,
verify_id_token_msg))
elif subject is None or not isinstance(subject, six.string_types):
error_message = ('Firebase ID token has no "sub" (subject) '
'claim. ') + verify_id_token_msg
elif not subject:
error_message = ('Firebase ID token has an empty string "sub" '
'(subject) claim. ') + verify_id_token_msg
elif len(subject) > 128:
error_message = ('Firebase ID token has a "sub" (subject) '
'claim longer than 128 '
'characters. ') + verify_id_token_msg
if error_message:
raise ValueError(error_message)
verified_claims = google.oauth2.id_token.verify_firebase_token(
id_token,
request=_request,
audience=project_id)
verified_claims['uid'] = verified_claims['sub']
return verified_claims
class _AuthService(object):
def __init__(self, app):
self._token_generator = _TokenGenerator(app)
self._user_manager = _user_mgt.UserManager(app)
@property
def token_generator(self):
return self._token_generator
@property
def user_manager(self):
return self._user_manager