GeezerVison is showing github.com — Invalid JWT Token when using Service Account JSON · Issue #3100 · googleapis/google-cloud-python
Invalid JWT Token when using Service Account JSON #3100Description
- OS type and version
macOS Sierra running a Debian Jessie Docker Container
- Python version and virtual environment information
python --version
CPython 3.5.0, no virtual environment
- google-cloud-python version
pip show google-cloud, pip show google-<service> or pip freeze
google-cloud-bigquery==0.23.0
- Stacktrace if available
Traceback (most recent call last):
File "/usr/local/lib/python3.5/code.py", line 91, in runcode
exec(code, self.locals)
File "<console>", line 1, in <module>
File "/usr/local/lib/python3.5/site-packages/celery/local.py", line 191, in __call__
return self._get_current_object()(*a, **kw)
File "/app/warehouse/celery.py", line 53, in __call__
return super().__call__(pyramid_env["request"], *args, **kwargs)
File "/usr/local/lib/python3.5/site-packages/celery/app/task.py", line 379, in __call__
return self.run(*args, **kwargs)
File "/app/warehouse/packaging/tasks.py", line 58, in compute_trending
query.run()
File "/usr/local/lib/python3.5/site-packages/google/cloud/bigquery/query.py", line 364, in run
method='POST', path=path, data=self._build_resource())
File "/usr/local/lib/python3.5/site-packages/google/cloud/_http.py", line 299, in api_request
headers=headers, target_object=_target_object)
File "/usr/local/lib/python3.5/site-packages/google/cloud/_http.py", line 193, in _make_request
return self._do_request(method, url, headers, data, target_object)
File "/usr/local/lib/python3.5/site-packages/google/cloud/_http.py", line 223, in _do_request
body=data)
File "/usr/local/lib/python3.5/site-packages/google_auth_httplib2.py", line 187, in request
self._request, method, uri, request_headers)
File "/usr/local/lib/python3.5/site-packages/google/auth/credentials.py", line 116, in before_request
self.refresh(request)
File "/usr/local/lib/python3.5/site-packages/google/oauth2/service_account.py", line 318, in refresh
request, self._token_uri, assertion)
File "/usr/local/lib/python3.5/site-packages/google/oauth2/_client.py", line 143, in jwt_grant
response_data = _token_endpoint_request(request, token_uri, body)
File "/usr/local/lib/python3.5/site-packages/google/oauth2/_client.py", line 109, in _token_endpoint_request
_handle_error_response(response_body)
File "/usr/local/lib/python3.5/site-packages/google/oauth2/_client.py", line 59, in _handle_error_response
error_details, response_body)
google.auth.exceptions.RefreshError: ('invalid_grant: Invalid JWT Signature.', '{\n "error" : "invalid_grant",\n "error_description" : "Invalid JWT Signature."\n}')
- Steps to reproduce
Try to query anything in BigQuery using a service account with "Viewer" permissions and GOOGLE_APPLICATION_CREDENTIALS pointed to a JSON file downloaded when creating the service account.
- Code example
bq = bigquery.Client()
query = bq.run_sync_query(
""" SELECT project,
IF(
STDDEV(downloads) > 0,
(todays_downloads - AVG(downloads))/STDDEV(downloads),
NULL
) as zscore
FROM (
SELECT project,
date,
downloads,
FIRST_VALUE(downloads) OVER (
PARTITION BY project
ORDER BY DATE DESC
ROWS BETWEEN UNBOUNDED PRECEDING
AND UNBOUNDED FOLLOWING
) as todays_downloads
FROM (
SELECT file.project as project,
DATE(timestamp) AS date,
COUNT(*) as downloads
FROM `the-psf.pypi.downloads*`
WHERE _TABLE_SUFFIX BETWEEN
FORMAT_DATE(
"%Y%m%d",
DATE_ADD(CURRENT_DATE(), INTERVAL -31 day))
AND
FORMAT_DATE(
"%Y%m%d",
DATE_ADD(CURRENT_DATE(), INTERVAL -1 day))
GROUP BY file.project, date
)
)
GROUP BY project, todays_downloads
HAVING SUM(downloads) >= 5000
ORDER BY zscore DESC
"""
)
query.use_legacy_sql = False
query.run()Reacted by ChristianEspinoza, Marius Cobzarenco, Catherine19950122, Michoel Samuels and Will Hill Activitydhermes commented on Mar 6, 2017 First, thanks for all the work you do on packaging @dstufft!
@jonparrott Any ideas? @dstufft This probably belongs in https://github.com/GoogleCloudPlatform/google-auth-library-python/, but let's discuss here first.
I've seen an issue where an invalid grant was caused by the clock on the local machine being out of sync by 4+ hours with the real world, but even being wrong by 65 minutes (in either direction) would make one of the "issued at" and "expires" timestamps in the JWT be impossible. Reacted by Jonathan Ferreira, Aaron Berry, gieoon, Daniel, Jimmy Palelil, Jack Wootton, Aron Janarv, Mohamed Ilyes Dimassi, JonyMath, Rafael Silva Nercessian and 6 more Reacted by Kunal Khoche, Mohamed Ilyes Dimassi and Rafael Silva Nercessian theacodes commented on Mar 6, 2017 Yeah this is a weird one. I'll try to reproduce.
…theacodes commented on Mar 6, 2017 @dstufft I can't reproduce. :(
I can't really debug any further without asking you for sensitive information. Do you mind reaching out to me via email or hangouts? I'm jonwayne at google.com. dstufft commented on Mar 6, 2017 theacodes commented on Mar 6, 2017 As per email conversation with @dstufft, closing for now. Reacted by Bruce Ricard, Gwendal-LE-CREN, Patrick Park, Guilherme Berger, Shivam Gaur, Zufar Muhamadeev, Dan Farrell, Brad Solomon, sidnuk106, Qiwei Yang and 18 more Reacted by Yehia Abdulhamid, Henry, AlexMougenet, Mike Pietruszka and Nadav Dav hakanak commented on Apr 5, 2017 Hello,
I have the same problem. I am developing an application with C #.
How did you find a solution?
Thank you. liangjacky commented on Aug 17, 2017 Having the same problem as well on the java library.
trying to do
credential.refreshToken();
String token = credential.getRefreshToken();
and it fails at the first line, giving the exact same error.
Running from the console with the command:
gcloud auth application-default print-access-token
gives the same error as well. theacodes commented on Aug 17, 2017 @liangjacky can you check your system clock? This is a very strange error and is difficult to reproduce. Reacted by Vladislav Nikolayev, Sumit1673, man Q, Alejandrow26, Mardari Grigore, Mani Jassar, Iago Neres, Kofi Donhkon, Goodwill Hacking, Vlad Tuznychenko and 15 more Reacted by man Q, Mardari Grigore, Vlad Tuznychenko, Nicolas Goldenberg, Keyur Kansara, Caleb John and Qwertic Reacted by man Q, Mardari Grigore, Iago Neres, Goodwill Hacking, Nabil MEDIOUNI, Vlad Tuznychenko, Nicolas Goldenberg, Caleb John, Ahmad Hussain, HolyRave and 2 more Reacted by man Q, Søren Kristiansen, Mardari Grigore, Iago Neres, Brainy Josh, Goodwill Hacking, Vlad Tuznychenko, Nicolas Goldenberg, Rebeca Araripe, Caleb John and 1 more liangjacky commented on Aug 17, 2017 @jonparrott what about my system clock? Is there a specific command I should run? Sorry for being so layman, but I think the time on my macbook is correct? theacodes commented on Aug 17, 2017 Basically just ensuring it's not too far off. Are you getting the exact same error? The code you posted in your comment appears to be java/javascript not Python. liangjacky commented on Aug 17, 2017 I just synced my time with time.apple.com and and it didn't seem to change anything. Thanks for the suggestion though. To answer your question, I'm getting the exact same error.
invalid_grant + invalid JWT signature. Authenticating using the application-default, and a json key on disk. Reacted by Chandra Shekhar Sengupta and Thomas Young liangjacky commented on Aug 17, 2017 Sorry, it was an issue with the key I was using. Please ignore my comments. johnbalvin commented on Sep 19, 2019 I had the same problem in another programming language(golang) but think this can work on this language too.
I had that error because I was using a credential file that was deleted on my project, so I just create another credential file, that that solved it gauravshimpi commented on Dec 20, 2019 I am facing same issue in python3.
from dags.util.GCloudStorage import GCloudStorage
client = GCloudStorage(
"/home/gaurav/airflow/dags/script/gcp_credentials/my_gcs_credentials.json", ""project_name)
client.create_bucket("test_bucket")
===============================================================
Here's the GCloudStorage.py looks like:
from google.cloud import storage
from google.oauth2 import service_account
from google.api_core import exceptions
class GCloudStorage:
def __init__(self, credential_file_path, project_id):
"""
:param credential_file_path: credential File for Authentication.
:param project_id: project ID
"""
self.CREDENTIAL_FILE_PATH = credential_file_path
self.PROJECT_ID = project_id
self.DATASET_ID = None
def create_connection(self):
"""
Creates Connection with Google Cloud Storage and returns client.
:return client: Google Cloud Storage Client
"""
google_credentials = service_account.Credentials.from_service_account_file(self.CREDENTIAL_FILE_PATH)
# Construct a BigQuery client object.
client = storage.Client(project=self.PROJECT_ID, credentials=google_credentials)
return client
def create_bucket(self, bucket_name):
"""
Creates a new empty bucket.
:param bucket_name: name of the bucket.
:return responseMsg: success or other message.
"""
# Instantiates a client
storage_client = self.create_connection()
response = None
try:
bucket = storage_client.create_bucket(bucket_name)
print(bucket)
response = "Bucket {} created".format(bucket.name)
except exceptions.Conflict as error:
response = "Bucket Already Exist: {}".format(error.code)
return {"response": response}
def upload_blob(self, bucket_name, source_file_name, destination_blob_name):
"""
Uploads a file to the bucket.
:param bucket_name: bucketName
:param source_file_name: Source File Name
:param destination_blob_name: Destination Blob Name.
:return responseMsg: Success or failed response message.
"""
storage_client = self.create_connection()
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob(destination_blob_name)
print("BlobName ---> ", blob)
blob.upload_from_filename(source_file_name)
response = "File {} uploaded to {}".format(source_file_name, destination_blob_name)
print(response)
return {"response": response}
def delete_bucket(self, bucket_name):
"""
Deletes a bucket. The bucket must be empty.
:param bucket_name: bucket Name.
:return responseMsg: success or failed response message.
"""
# Instantiates a client
storage_client = self.create_connection()
bucket = storage_client.get_bucket(bucket_name)
bucket.delete()
response = "Bucket {} deleted".format(bucket.name)
return {"response": response}
=============================================================
when i run the above create bucket code it gives me below error:
Traceback (most recent call last):
File "/home/gaurav/airflow/dags/util/test cloud.py", line 7, in
client.create_bucket("test_bucket")
File "/home/gaurav/airflow/dags/util/GCloudStorage.py", line 37, in create_bucket
bucket = storage_client.create_bucket(bucket_name)
File "/home/gaurav/airflow/venv/lib/python3.6/site-packages/google/cloud/storage/client.py", line 436, in create_bucket
_target_object=bucket,
File "/home/gaurav/airflow/venv/lib/python3.6/site-packages/google/cloud/_http.py", line 417, in api_request
timeout=timeout,
File "/home/gaurav/airflow/venv/lib/python3.6/site-packages/google/cloud/_http.py", line 275, in _make_request
method, url, headers, data, target_object, timeout=timeout
File "/home/gaurav/airflow/venv/lib/python3.6/site-packages/google/cloud/_http.py", line 313, in _do_request
url=url, method=method, headers=headers, data=data, timeout=timeout
File "/home/gaurav/airflow/venv/lib/python3.6/site-packages/google/auth/transport/requests.py", line 277, in request
self.credentials.before_request(auth_request, method, url, request_headers)
File "/home/gaurav/airflow/venv/lib/python3.6/site-packages/google/auth/credentials.py", line 124, in before_request
self.refresh(request)
File "/home/gaurav/airflow/venv/lib/python3.6/site-packages/google/oauth2/service_account.py", line 334, in refresh
access_token, expiry, _ = _client.jwt_grant(request, self._token_uri, assertion)
File "/home/gaurav/airflow/venv/lib/python3.6/site-packages/google/oauth2/_client.py", line 153, in jwt_grant
response_data = _token_endpoint_request(request, token_uri, body)
File "/home/gaurav/airflow/venv/lib/python3.6/site-packages/google/oauth2/_client.py", line 124, in _token_endpoint_request
_handle_error_response(response_body)
File "/home/gaurav/airflow/venv/lib/python3.6/site-packages/google/oauth2/_client.py", line 60, in _handle_error_response
raise exceptions.RefreshError(error_details, response_body)
google.auth.exceptions.RefreshError: ('invalid_grant: Invalid JWT Signature.', '{\n "error": "invalid_grant",\n "error_description": "Invalid JWT Signature."\n}')
Process finished with exit code 1
I am newbie to GCP, so any silly mistakes will be helpful to me.
Thank you in advance. webcat12345 commented on Feb 1, 2020 Really a good catch!!!
#3100 (comment)
With some reason my system clock was 2 hours ahead and setting it back to correct time, all worked well. Reacted by Dalia Zahran, Elvis Sun, Neal Coleman and takuDzwa NathanaelZondo commented on Feb 7, 2020 It was the time that was causing this error. I took my battery out and the laptop lost track of time. Now after reading your comments I just updated the time and everything worked well. Thank you guys. ggabriel96 commented on Sep 11, 2020
Ok, I found as issue with Docker for Mac docker/for-mac#2076 (a couple related issues actually, but this one pretty clearly covers the problem). The time of the VM that runs containers drifts from system time, and doesn't appear to reset itself properly. Stopping and restarting Docker for Mac fixed the issue for me.
I was having the same problem here on Linux and restarting the Docker service solved it for me. Too bad I didn't check the time inside my container before restarting Docker.
Thanks a lot ❤️ abhishek-jaisingh commented on Dec 7, 2020
First, thanks for all the work you do on packaging @dstufft!
@jonparrott Any ideas? @dstufft This probably belongs in https://github.com/GoogleCloudPlatform/google-auth-library-python/, but let's discuss here first.
I've seen an issue where an invalid grant was caused by the clock on the local machine being out of sync by 4+ hours with the real world, but even being wrong by 65 minutes (in either direction) would make one of the "issued at" and "expires" timestamps in the JWT be impossible.
I was having the same problem while using GCS, thanks a bunch!
The time of individual machines had somehow drifted, syncing via NTP fixed it. j3pic commented on Dec 17, 2020 I'm running into this issue, and I know for certain that the time being used by the SDK is the correct time. I extracted the exact JWT that was being posted and verified that the exp being posted was in the future. The iat timestamp was set a few minutes in the past. kenyerman commented on Jan 24, 2021 I have this issue but my code is deployed as a cloud function. What should i do? Reacted by DC, nitishxp, James Lindsay and Risal Fajar Amiyardi abhinavkbij commented on Sep 3, 2021 I was getting the same error in Python 3.7. Created a new key and set it in the GOOGLE_APPLICATION_CREDENTIALS env var, somehow the error went away. Not sure it will work for everyone but worth a try. aszeli commented on Sep 21, 2021 I was getting this error. Turns out it had been too long since I'd run gcloud auth activate-service-account and my credentials had expired Jacksongreenhenry commented on Nov 24, 2023 ===This is the problem i am facing in python 3.7, i saw a comment to correct my system clock, i did but it still showed the same error.
Below is the code and the error it gave me===
import firebase_admin
from firebase_admin import credentials
from firebase_admin import db
cred = credentials.Certificate("serviceAccountKey.json")
firebase_admin.initialize_app(cred, {
'databaseURL': "https://faceattendancerealtime-2b9ec-default-rtdb.firebaseio.com/"
})
ref = db.reference('Students')
data = {
"321654":
{
"name": "Jackson Green",
"major": "Engineering",
"starting_year": 2017,
"total_attendance": 6,
"standing": "G",
"year": 4,
"last_attendance_time": "2022-12-11 00:54:34"
}
}
for key, value in data.items():
ref.child(key).set(value)
===Above is the code===
===Below is the error i recieved===
C:\Users\Hysoka\PycharmProjects\FaceRegcognitionRealTimeDatabase\venv\lib\site-packages\google\auth_init_.py:55: Python37DeprecationWarning: After January 1, 2024, new releases of this library will drop support for Python 3.7. More details about Python 3.7 support can be found at https://cloud.google.com/python/docs/python37-sunset/
warnings.warn(message, Python37DeprecationWarning)
C:\Users\Hysoka\PycharmProjects\FaceRegcognitionRealTimeDatabase\venv\lib\site-packages\google\oauth2_init_.py:40: Python37DeprecationWarning: After January 1, 2024, new releases of this library will drop support for Python 3.7. More details about Python 3.7 support can be found at https://cloud.google.com/python/docs/python37-sunset/
warnings.warn(message, Python37DeprecationWarning)
Traceback (most recent call last):
File "C:\Users\Hysoka\PycharmProjects\FaceRegcognitionRealTimeDatabase\AddDataToDatabase.py", line 46, in
ref.child(key).set(value)
File "C:\Users\Hysoka\PycharmProjects\FaceRegcognitionRealTimeDatabase\venv\lib\site-packages\firebase_admin\db.py", line 264, in set
self._client.request('put', self._add_suffix(), json=value, params='print=silent')
File "C:\Users\Hysoka\PycharmProjects\FaceRegcognitionRealTimeDatabase\venv\lib\site-packages\firebase_admin\db.py", line 929, in request
return super(_Client, self).request(method, url, **kwargs)
File "C:\Users\Hysoka\PycharmProjects\FaceRegcognitionRealTimeDatabase\venv\lib\site-packages\firebase_admin_http_client.py", line 118, in request
resp = self._session.request(method, self.base_url + url, **kwargs)
File "C:\Users\Hysoka\PycharmProjects\FaceRegcognitionRealTimeDatabase\venv\lib\site-packages\google\auth\transport\requests.py", line 538, in request
self.credentials.before_request(auth_request, method, url, request_headers)
File "C:\Users\Hysoka\PycharmProjects\FaceRegcognitionRealTimeDatabase\venv\lib\site-packages\google\auth\credentials.py", line 175, in before_request
self.refresh(request)
File "C:\Users\Hysoka\PycharmProjects\FaceRegcognitionRealTimeDatabase\venv\lib\site-packages\google\oauth2\service_account.py", line 439, in refresh
request, self._token_uri, assertion
File "C:\Users\Hysoka\PycharmProjects\FaceRegcognitionRealTimeDatabase\venv\lib\site-packages\google\oauth2_client.py", line 314, in jwt_grant
metrics.API_CLIENT_HEADER: metrics.token_request_access_token_sa_assertion()
File "C:\Users\Hysoka\PycharmProjects\FaceRegcognitionRealTimeDatabase\venv\lib\site-packages\google\oauth2_client.py", line 279, in _token_endpoint_request
_handle_error_response(response_data, retryable_error)
File "C:\Users\Hysoka\PycharmProjects\FaceRegcognitionRealTimeDatabase\venv\lib\site-packages\google\oauth2_client.py", line 73, in _handle_error_response
error_details, response_data, retryable=retryable_error
google.auth.exceptions.RefreshError: ('invalid_grant: Invalid JWT: Token must be a short-lived token (60 minutes) and in a reasonable timeframe. Check your iat and exp values in the JWT claim.', {'error': 'invalid_grant', 'error_description': 'Invalid JWT: Token must be a short-lived token (60 minutes) and in a reasonable timeframe. Check your iat and exp values in the JWT claim.'})
===I would really need help here thank you=== parthea commented on Nov 24, 2023
MetadataMetadataDevelopmentNo branches or pull requestsIssue actions
|