firbase_admin auth firbase_admin auth and verify_id_token方法的代币使用过早的错误

发布于 2025-01-22 04:00:50 字数 504 浏览 4 评论 0原文

每当我运行时,

from firebase_admin import auth
auth.verify_id_token(firebase_auth_token)

它都会引发以下错误:

Token used too early, 1650302066 < 1650302067. Check that your computer's clock is set correctly.

我知道基本的Google Auth Apis确实会检查令牌的时间,但是概述在这里应该有一个10秒的时钟偏斜。显然,我的服务器时间停在1秒钟,但是即使这远低于允许的10秒偏斜,运行仍会失败。有办法解决这个问题吗?

Whenever I run

from firebase_admin import auth
auth.verify_id_token(firebase_auth_token)

It throws the following error:

Token used too early, 1650302066 < 1650302067. Check that your computer's clock is set correctly.

I'm aware that the underlying google auth APIs do check the time of the token, however as outlined here there should be a 10 second clock skew. Apparently, my server time is off by 1 second, however running this still fails even though this is well below the allowed 10 second skew. Is there a way to fix this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

无人问我粥可暖 2025-01-29 04:00:50

这就是firebase_admin.verify_id_token验证令牌的方式:

verified_claims = google.oauth2.id_token.verify_token(
                    token,
                    request=request,
                    audience=self.project_id,
                    certs_url=self.cert_url)

(...)的定义。

def verify_token(
    id_token,
    request,
    audience=None,
    certs_url=_GOOGLE_OAUTH2_CERTS_URL,
    clock_skew_in_seconds=0,
):

这就是google.oauth2.id_token.doken.verify_token 将其传递给它,因此使用0的默认值,并且由于您的服务器时钟停止了1秒钟,因此verify_token中的检查失败。

我认为这是Firebase_admin.verify_id_token中的一个错误,也许您可​​以针对Firebase Admin SDK打开问题,但是除此之外,您只能确保您的时钟是精确的,或者比实际时间更早显示时间

我实际上打开了一个 for for Firebase/firebase-admin-python和github上的问题根据 pull request> ...

如果并且何时合并了拉动请求,则允许服务器的时钟停止长达一分钟。

This is how the firebase_admin.verify_id_token verifies the token:

verified_claims = google.oauth2.id_token.verify_token(
                    token,
                    request=request,
                    audience=self.project_id,
                    certs_url=self.cert_url)

and this is the definition of google.oauth2.id_token.verify_token(...)

def verify_token(
    id_token,
    request,
    audience=None,
    certs_url=_GOOGLE_OAUTH2_CERTS_URL,
    clock_skew_in_seconds=0,
):

As you can see, the function verify_token allows to specify a "clock_skew_in_seconds" but the firebase_admin function is not passing it along, thus the the default of 0 is used and since your server clock is off by 1 second, the check in verify_token fails.

I would consider this a bug in firebase_admin.verify_id_token and maybe you can open an issue against the firebase admin SDK, but other than that you can only make sure, your clock is either exact or shows a time EARLIER than the actual time

Edit:

I actually opened an issue on GitHub for firebase/firebase-admin-Python and created an according pull request since I looked at all the source files already anyway...

If and when the pull request is merged, the server's clock is allowed to be off by up to a minute.

生活了然无味 2025-01-29 04:00:50

在Windows 11 PC中运行LocalHost时,我遇到了同样的问题。我通过控制面板找到了一个临时解决方案。日期和时间&gt;互联网时间并将同步服务器更改为time.google.com。如果错误在重新打开我的机器后持续存在,请及时&amp;现在在设置中的时间并在其他设置上按Sync,将其修复,直到关闭机器为止。

I'm having the same problem when running the localhost in my windows 11 PC.I've found a temporary solution by going to Control Panel > Date and Time > Internet Time and changing the synchronization server to time.google.com. If the error persists after re-opening my machine, going to date & time in settings and pressing sync now on additional settings, fixes it until the machine is shut down.

坚持沉默 2025-01-29 04:00:50

也有类似的问题,通过在验证定义`中添加“ clock_skew_in_seconds = 10”来解决它。

   def validate(auth_token):
    """
    validate method Queries the Google oAUTH2 api to fetch the user info
    """
    try:
        idinfo = id_token.verify_oauth2_token(
            auth_token, requests.Request(), clock_skew_in_seconds=10)

        if 'accounts.google.com' in idinfo['iss']:
            return idinfo

    except:
        return "The token is either invalid or has expired"`

Had similar problem, solved it by adding "clock_skew_in_seconds=10" in validating definition `

   def validate(auth_token):
    """
    validate method Queries the Google oAUTH2 api to fetch the user info
    """
    try:
        idinfo = id_token.verify_oauth2_token(
            auth_token, requests.Request(), clock_skew_in_seconds=10)

        if 'accounts.google.com' in idinfo['iss']:
            return idinfo

    except:
        return "The token is either invalid or has expired"`
森林很绿却致人迷途 2025-01-29 04:00:50

我看到这仍然没有拉。为了解决我,我做了以下操作,因此可以在正确的时间验证令牌。

@staticmethod
def decode_token(id_token: str) -> FirebaseToken:
    """Decode a Firebase ID token.

    Args:
        id_token (str): A valid Firebase `id_token`, this will be checked to determine if:
            * The token is present and a valid JWT.
            * The token has NOT expired.
            * The token has NOT been revoked.
            * The token has been issued under the correct GCP credentials (API key).

    Returns:
        FirebaseToken: A serialized Firebase ID token.

    Raises:
        HTTPException: If the token fails it's validation.
    """
    try:
        
        payload = JWTBearer.verify_token(id_token)
    except ValueError as err:
        raise HTTPException(
            status_code=401, detail="Unable to verify token"
        ) from err
    except (
        ExpiredIdTokenError,
        InvalidIdTokenError,
        RevokedIdTokenError,
    ) as err:
        # this happens on localhost all the time.
        str_err = str(err)
        if (str_err.find("Token used too early") > -1):
            times = str_err.split(",")[1].split("<")
            time = int(times[1]) - int(times[0])
            sleep(time)
            return JWTBearer.decode_token(id_token)
        raise HTTPException(
            status_code=403, detail=err.default_message
        ) from err
    except CertificateFetchError as err:
        raise HTTPException(
            status_code=500,
            detail="Failed to fetch public key certificates",
        ) from err

    return FirebaseToken(**payload)

I see this still isn't pulled. To fix it for me I did the following so it would retry to validate the token at the correct time.

@staticmethod
def decode_token(id_token: str) -> FirebaseToken:
    """Decode a Firebase ID token.

    Args:
        id_token (str): A valid Firebase `id_token`, this will be checked to determine if:
            * The token is present and a valid JWT.
            * The token has NOT expired.
            * The token has NOT been revoked.
            * The token has been issued under the correct GCP credentials (API key).

    Returns:
        FirebaseToken: A serialized Firebase ID token.

    Raises:
        HTTPException: If the token fails it's validation.
    """
    try:
        
        payload = JWTBearer.verify_token(id_token)
    except ValueError as err:
        raise HTTPException(
            status_code=401, detail="Unable to verify token"
        ) from err
    except (
        ExpiredIdTokenError,
        InvalidIdTokenError,
        RevokedIdTokenError,
    ) as err:
        # this happens on localhost all the time.
        str_err = str(err)
        if (str_err.find("Token used too early") > -1):
            times = str_err.split(",")[1].split("<")
            time = int(times[1]) - int(times[0])
            sleep(time)
            return JWTBearer.decode_token(id_token)
        raise HTTPException(
            status_code=403, detail=err.default_message
        ) from err
    except CertificateFetchError as err:
        raise HTTPException(
            status_code=500,
            detail="Failed to fetch public key certificates",
        ) from err

    return FirebaseToken(**payload)
回眸一遍 2025-01-29 04:00:50

转到verify_id_token() auth.py中的功能和concep_skew_seconds = 0 to copte> copte_skew_seconds = 60。这对我来说很好。

Go to verify_id_token() function in auth.py and change clock_skew_seconds=0 to clock_skew_seconds=60. It is working fine for me.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文