Skip to content

onAuthStateChange not triggered when JWT expired #452

Closed as not planned

Description

@KirioXX

Describe the bug
We had this week quite a lot of users where the JWT expired.
There users where not logged out instead they had to close and reopen the app to trigger the logout.

In our logs we have seen a lot of these errors:

data:text/text;charset=utf-8,
PostgrestException(message: JWT expired, code: PGRST301, details: Unauthorized, hint: null)

When the exception was thrown, this was the stack:
0		PostgrestBuilder._parseResponse (package:postgrest/src/postgrest_builder.dart:323:0)
1		PostgrestBuilder._execute (package:postgrest/src/postgrest_builder.dart:198:0)
2		PostgrestBuilder.then (package:postgrest/src/postgrest_builder.dart:400:0)

To Reproduce
Steps to reproduce the behavior:

  1. Setup a listener to listen for onAuthStateChange (we use a bloc cubit for that )
  2. Login
  3. Let the JWT expire
  4. Try to make a request

Expected behavior
User is getting logged out either when the JWT expires or when the try to make a request.

Screenshots

Version (please complete the following information):
On Linux/macOS
Please run dart pub deps | grep -E "supabase|gotrue|postgrest|storage_client|realtime_client|functions_client" in your project directory and paste the output here.

│   └── supabase_flutter...
│   └── supabase_flutter...
│   └── supabase_flutter...
│   ├── supabase_flutter...
│   ├── supabase_flutter...
│   └── supabase_flutter...
│   ├── supabase_flutter...
│   └── supabase_flutter...
│   ├── supabase_flutter...
│   └── supabase_flutter...
│   └── supabase_flutter...
│   └── supabase_flutter...
├── supabase_flutter 1.7.0
│   ├── supabase 1.6.3
│   │   ├── functions_client 1.1.1
│   │   ├── gotrue 1.6.0
│   │   ├── postgrest 1.2.3
│   │   ├── realtime_client 1.0.3
│   │   ├── storage_client 1.3.0

On Windows
Please run dart pub deps | findstr "supabase gotrue postgrest storage_client realtime_client functions_client" in your project directory and paste the output here.

Additional context
Add any other context about the problem here.

Activity

  1. added
    bug
    on Apr 25, 2023
  2. Vinzent03 commented on Apr 25, 2023

    @Vinzent03
    Collaborator

    gotrue 1.6.0 got just a few minutes ago released. Do you really still experience this issue? What version of gotrue where the production app using? What jwt expiry time have you set?

  3. KirioXX commented on Apr 26, 2023

    @KirioXX
    Author

    Thanks for the quick response @Vinzent03.
    That is a very good point the current production version is still on gotrue 1.4.2:

    ├── supabase_flutter 1.4.0
    │   ├── supabase 1.5.1
    │   │   ├── functions_client 1.0.2
    │   │   ├── gotrue 1.4.2
    │   │   ├── postgrest 1.2.2
    │   │   ├── realtime_client 1.0.2
    │   │   ├── storage_client 1.2.2

    Could that be the issue?

  4. Vinzent03 commented on Apr 26, 2023

    @Vinzent03
    Collaborator

    There was a fix in 1.5.6 about jwt expiry margins. This may be the cause.

  5. KirioXX commented on Apr 26, 2023

    @KirioXX
    Author

    Thank you very much Vinzent03.
    We actually have a new release going out to the first users today, which uses 1.5.6.
    I will keep you posted if the new version resolves it.

  6. Vinzent03 commented on Apr 26, 2023

    @Vinzent03
    Collaborator

    It might be important to update to 1.5.7 though, depending on how important the session emitted by the inAuthStateChange stream is.

  7. KirioXX commented on Apr 26, 2023

    @KirioXX
    Author

    Sorry I meant we are on 1.5.7 😅

  8. KirioXX commented on May 5, 2023

    @KirioXX
    Author

    @Vinzent03 we rolled out our new app version to some test device. So far everything looks good.
    But we got this error yesterday and it seems to be stuck in a loop:

    data:text/text;charset=utf-8,
    AuthException(message: Invalid Refresh Token: Refresh Token Not Found, statusCode: 400)
    
    When the exception was thrown, this was the stack:
    0		GotrueFetch.request (package:gotrue/src/fetch.dart:99:0)
    1		GoTrueClient._callRefreshToken (package:gotrue/src/gotrue_client.dart:669:0)
    2		GoTrueClient.recoverSession (package:gotrue/src/gotrue_client.dart:549:0)
    3		SupabaseAuth.initialize (package:supabase_flutter/src/supabase_auth.dart:104:0)
    4		Supabase.initialize (package:supabase_flutter/src/supabase.dart:91:0)
    5		_initSupabase (package:tusks/main.dart:67:0)
    6		main (package:tusks/main.dart:24:0)
    7		main (package:tusks/main_production.dart:18:0)

    Can that be related to the JWT issue?

  9. Vinzent03 commented on May 5, 2023

    @Vinzent03
    Collaborator

    You should get logged out when this error comes up. You get this error for example when you sign out on another device.

  10. KirioXX commented on May 12, 2023

    @KirioXX
    Author

    Hi @Vinzent03, we had yesterday again a user that didn't get log out even though the request returned 401 codes.
    Is there anything that we could miss when we listen to onAuthStateChange?

  11. Vinzent03 commented on May 12, 2023

    @Vinzent03
    Collaborator

    We currently only sign out on the specific error message Invalid Refresh Token: Refresh Token Not Found. I don't know what the reason for a 401 response is. We emit the error via addError to the onAuthDtateChange stream, where you could react to that.

  12. KirioXX commented on May 12, 2023

    @KirioXX
    Author

    Thanks for the quick response @Vinzent03.
    If it helps, this is full response:

    Response
      Headers:
       access-control-allow-origin: "*"
       content-type: "application/json; charset=utf-8"
       x-kong-upstream-latency: "0"
       alt-svc: "h3=":443"; ma=86400, h3-29=":443"; ma=86400"
       via: "kong/2.8.1"
       server: "cloudflare"
       sb-gateway-version: "1"
       transfer-encoding: "chunked"
       cf-cache-status: "DYNAMIC"
       date: "Thu, 11 May 2023 21:51:43 GMT"
       x-kong-proxy-latency: "1"
       strict-transport-security: "max-age=2592000; includeSubDomains"
       connection: "keep-alive"
       cf-ray: "7c5da514af510fd3-LAX"
       vary: "Accept-Encoding"
       www-authenticate: "Bearer error="invalid_token", error_description="JWT expired""
      Body:
       code: "PGRST301"
       message: "JWT expired"
       details: null
       hint: null
    

    The logs also say that there was 1 slow request before the failing once, could it be that the JWT was invalidated because the refresh request was to slow? Sadly I miss a couple network request logs.

  13. Vinzent03 commented on May 12, 2023

    @Vinzent03
    Collaborator

    That seems to be the response of a call to postgrest which failed, because the call to refresh the jwt didn't work.

    could it be that the JWT was invalidated because the refresh request was to slow?
    Definitely not, because jwts can't be manually invalidated. Only after the expiry time.

    Can you see how slow exactly the previous request was and where it went? Maybe the call to the token endpoint to refresh the jwt hasn't finished yet?

  14. KirioXX commented on May 12, 2023

    @KirioXX
    Author

    I can see the 100 failed requests and they all tried to fetch the same resource:

    {
      "status": 401,
      "response_time": 198.431,
      "method": "GET",
      "response_headers": {
        "access-control-allow-origin": "*",
        "content-type": "application/json; charset=utf-8",
        "x-kong-upstream-latency": "0",
        "alt-svc": "h3=\":443\"; ma=86400, h3-29=\":443\"; ma=86400",
        "via": "kong/2.8.1",
        "server": "cloudflare",
        "sb-gateway-version": "1",
        "transfer-encoding": "chunked",
        "cf-cache-status": "DYNAMIC",
        "date": "Thu, 11 May 2023 21:49:44 GMT",
        "x-kong-proxy-latency": "1",
        "strict-transport-security": "max-age=2592000; includeSubDomains",
        "connection": "keep-alive",
        "cf-ray": "7c5da231ee9d0fd3-LAX",
        "vary": "Accept-Encoding",
        "www-authenticate": "Bearer error=\"invalid_token\", error_description=\"JWT expired\""
      },
      "date": 1683841784800,
      "request": "",
      "headers": {
        "Accept-Profile": "public",
        "apikey": "XXXX",
        "X-Client-Info": "supabase-flutter/1.7.0",
        "Authorization": "Bearer XXXX"
      },
      "response": {
        "code": "PGRST301",
        "message": "JWT expired",
        "details": null,
        "hint": null
      },
      "url": "https://XXXX/rest/v1/job_cards?select=%2A&job_card_id=eq.ae44c164-a38b-413a-9e61-ab89512a4bb7&limit=1"
    }
  15. KirioXX commented on May 15, 2023

    @KirioXX
    Author

    Hi @Vinzent03,
    I just wanted to check if there are any updates on this issue?
    If that is nothing new could you advice use how we could get around this issue?
    Thank you

  16. 37 remaining items

  17. Vinzent03 commented on Jul 30, 2023

    @Vinzent03
    Collaborator

    Yeah your code should generally work. Two things though to consider

    1. You have no margin for the expiry check and the actual validation on the server. I would use the newly added isExpired getter on the session, because it adds a 5 second buffer.
    2. As already stated in another post, if the refresh token is already used or invalidated because of a sign out of the same account, the token refresh fails and you have to sign in again. The client should automatically log you out.
  18. KirioXX commented on Aug 24, 2023

    @KirioXX
    Author

    Hi @dshukertjr, sorry for the delayed response.
    We where not able to test it, but we just started rolling out to a new customer so I should be able to give you feedback in a couple days on this issue.
    What though noticed is that we have with the new version some strange behaviour with the streams, I created a new issue for that: #604

  19. bretmh commented on Oct 27, 2023

    @bretmh

    Error: PostgrestException(message: JWT expired, code: PGRST301, details: Unauthorized, hint: null).

    I'm curious about the progress of this issue. Starting my application I am already logged in, the event AuthChangeEvent.signedIn is fired (session is recovered).

    I've checked the calls the state changes and also the session recovery in supabase_auth.dart it all looks fine. It's failing on an RPC call, I've also checked the postgrest_builder.dart and the configuration of the AuthHttpClient. There is nothing wrong, however, the backend doesn't like it. How I've determined it's okay is the expiresAt and currentTime values being used results in the token are still valid.

  20. dshukertjr commented on Jan 22, 2024

    @dshukertjr
    Member

    I'm going to close this issue as we have implemented many updates to mitigate the original issue of the access token not refreshing properly, but if anyone is still experiencing the same issue, please let us know in the comments and we will re-open this one.

  21. tomekit commented on Jan 22, 2024

    @tomekit

    In our case we get expired token in our login handler every time when user starts the app when stored access token (1h expiration time already expired)

    Likely because: tokenRefreshed event is sent before: _saveSession finishes, so any code that relies on: tokenRefreshed event and: Supabase.instance.client will generate 403 until the _saveSession finalizes.

    gotrue-2.3.0/lib/src/gotrue_client.dart

      _saveSession(authResponse.session!);
          if (!_refreshTokenCompleter!.isCompleted) {
            _refreshTokenCompleter!.complete(authResponse);
          }
    
          notifyAllSubscribers(AuthChangeEvent.tokenRefreshed);
  22. dshukertjr commented on Jan 22, 2024

    @dshukertjr
    Member

    @tomekit

    In our case we get expired token in our login handler every time when user starts the app when stored access token (1h expiration time already expired)

    The token being expired on app launch shouldn't be an issue as the token should be automatically refreshed before making an API request.

    so any code that relies on: tokenRefreshed

    Do you have any code that you use that relies on tokenRefreshed event?

    What exactly are you experiencing? Do you get PostgrestException with error code PGRST301 thrown when making API request?

  23. added
    auth
    on Jul 22, 2024
  24. added a commit that references this issue on Feb 5, 2026
    4f53366
  25. github-actions commented on Mar 22, 2026

    @github-actions
    Contributor

    This issue has been inactive for 180 days.
    It will be automatically closed in 30 days if there is no further activity.

    If you believe this issue is still relevant, please leave a comment to keep it open.
    Thank you for your contributions!

  26. github-actions commented on Apr 26, 2026

    @github-actions
    Contributor

    This issue was automatically closed due to inactivity.

    If you believe this is still relevant, feel free to reopen it or create a new issue with updated information.

  27. added a commit that references this issue on Jun 10, 2026
    de2adf9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Staleauthbug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions