google-cloud-python icon indicating copy to clipboard operation
google-cloud-python copied to clipboard

Invalid JWT Token when using Service Account JSON

Open dstufft opened this issue 9 years ago • 28 comments

  1. OS type and version

macOS Sierra running a Debian Jessie Docker Container

  1. Python version and virtual environment information python --version

CPython 3.5.0, no virtual environment

  1. google-cloud-python version pip show google-cloud, pip show google-<service> or pip freeze

google-cloud-bigquery==0.23.0

  1. 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}')
  1. 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.

  1. 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()

dstufft avatar Mar 06 '17 03:03 dstufft

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 :heart:

ggabriel96 avatar Sep 11 '20 18:09 ggabriel96

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.

abhishek-jaisingh avatar Dec 07 '20 10:12 abhishek-jaisingh

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.

j3pic avatar Dec 17 '20 00:12 j3pic

I have this issue but my code is deployed as a cloud function. What should i do?

kenyerman avatar Jan 24 '21 18:01 kenyerman

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.

abhinavkbij avatar Sep 03 '21 12:09 abhinavkbij

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

aszeli avatar Sep 21 '21 17:09 aszeli

===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===

Jacksongreenhenry avatar Nov 24 '23 18:11 Jacksongreenhenry

Hi @Jacksongreenhenry,

Please could you file a new support request in https://github.com/googleapis/google-auth-library-python via this link: https://github.com/googleapis/google-auth-library-python/issues/new?assignees=&labels=&projects=&template=support_request.md?

parthea avatar Nov 24 '23 18:11 parthea