Skip to content

Custom LocalStorage logs out user instead of refreshing session #895

Closed as not planned

Description

@micheltucker

Describe the bug

I need to maintain a Custom LocalStorage and followed the description here: https://pub.dev/documentation/supabase_flutter/latest/#a-idcustom-localstorageacustom-localstorage

I am encountering a recurring issue in my iOS Flutter application that integrates Supabase with custom LocalStorage for authentication. Specifically, when attempting to automatically recover a user session after the application has been in the background, the refresh token fails with an "Invalid Refresh Token: Already Used" error. This error is consistently triggering a sign-out event, effectively logging the user out and hindering session persistence across app launches or background returns.

To Reproduce
Steps to reproduce the behavior:

  1. Log in to the application to initiate a session with Supabase.
  2. Send the application to the background for an extended period or until the access token is likely expired.
  3. Resume the application, triggering the automatic session recovery process.
  4. Observe that instead of refreshing the session, an error occurs, and the user is signed out.

Expected behavior
The application should silently refresh the session using the stored refresh token when the access token has expired, without any intervention from the user, maintaining the user's logged-in state across app uses. This works for the default localstorage of Supabase.

Actual beheavior
When attempting to refresh the session, the application signs out and throws an "Invalid Refresh Token: Already Used" error, resulting in the user being signed out. The relevant log outputs are as follows:


flutter: **** onAuthStateChange: AuthChangeEvent.signedOut
flutter: Auth state change detected
flutter: AuthException(message: Invalid Refresh Token: Already Used, statusCode: 400)
flutter: #0      GotrueFetch.request (package:gotrue/src/fetch.dart:99:7)
flutter: <asynchronous suspension>
flutter: #1      GoTrueClient._callRefreshToken (package:gotrue/src/gotrue_client.dart:1087:24)
flutter: <asynchronous suspension>
flutter: #2      GoTrueClient.recoverSession (package:gotrue/src/gotrue_client.dart:928:16)
flutter: <asynchronous suspension>
flutter: #3      SupabaseAuth._recoverSupabaseSession (package:supabase_flutter/src/supabase_auth.dart:127:7)
flutter: <asynchronous suspension>
[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: AuthException(message: Invalid Refresh Token: Already Used, statusCode: 400)
#0      GotrueFetch.request (package:gotrue/src/fetch.dart:99:7)
<asynchronous suspension>
#1      GoTrueClient._callRefreshToken (package:gotrue/src/gotrue_client.dart:1087:24)
<asynchronous suspension>
#2      GoTrueClient.recoverSession (package:gotrue/src/gotrue_client.dart:928:16)
<asynchronous suspension>
#3      SupabaseAuth._recoverSupabaseSession (package:supabase_flutter/src/supabase_auth.dart:127:7)
<asynchronous suspension>
[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: AuthException(message: Invalid Refresh Token: Already Used, statusCode: 400)
#0      GotrueFetch.request (package:gotrue/src/fetch.dart:99:7)
<asynchronous suspension>
#1      GoTrueClient._callRefreshToken (package:gotrue/src/gotrue_client.dart:1087:24)
<asynchronous suspension>
#2      GoTrueClient.recoverSession (package:gotrue/src/gotrue_client.dart:928:16)
<asynchronous suspension>
#3      SupabaseAuth._recoverSupabaseSession (package:supabase_flutter/src/supabase_auth.dart:127:7)
<asynchronous suspension>

Version (please complete the following information):
├── supabase_flutter 2.3.4
│ ├── supabase 2.0.8
│ │ ├── functions_client 2.0.0
│ │ ├── gotrue 2.5.1
│ │ ├── postgrest 2.1.1
│ │ ├── realtime_client 2.0.1
│ │ ├── storage_client 2.0.1

Activity

  1. added
    bug
    on Apr 22, 2024
  2. micheltucker commented on Apr 22, 2024

    @micheltucker
    Author

    cc: @dshukertjr
    I saw you working on the custom LocalStorage implementation and maybe you can help :)

  3. micheltucker commented on Apr 22, 2024

    @micheltucker
    Author

    Ok I updated to supabase_flutter: ^2.5.1 after seeing the 2.5.0 changelog description and I cannot reproduce the bug anymore.

    Could somebody confirm that that indeed fixed the custom LocalStorage implementation?

    Update:
    Another interesting thing I noticed with the update is that I do not see the app continuously refreshing the tokens in the background anymore.

    Update 2:
    Ok, was able to reproduce it again, but with a more informative error log.

    flutter: **** onAuthStateChange: AuthChangeEvent.signedOut
    flutter: Removing session data...
    flutter: Auth state change detected
    [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Null check operator used on a null value
    #0      AuthHttpClient.send (package:supabase/src/auth_http_client.dart:20:37)
    <asynchronous suspension>
    #1      BaseClient._sendUnstreamed (package:http/src/base_client.dart:93:32)
    <asynchronous suspension>
    #2      PostgrestBuilder._execute (package:postgrest/src/postgrest_builder.dart:130:20)
    <asynchronous suspension>
    #3      PostgrestBuilder.then (package:postgrest/src/postgrest_builder.dart:372:24)
    <asynchronous suspension>
    
  4. added
    auth
    on Apr 22, 2024
  5. dshukertjr commented on Apr 22, 2024

    @dshukertjr
    Member

    @micheltucker Whether your implementation of the custom local storage works fine or not depends on the implementation itself. The error you were encountering makes me think that there is something wrong with the implementation, and the application is not able to update the refresh token with the new one whenever it's issued.

    The update on v2.5.0 may have reduced how often token refresh happens, but I don't think it fixed the root cause of what you were having trouble with. All of that, however, is just speculation, and we cannot confirm anything unless you share your implementation of your custom local storage.

  6. micheltucker commented on Apr 22, 2024

    @micheltucker
    Author

    @micheltucker Whether your implementation of the custom local storage works fine or not depends on the implementation itself. The error you were encountering makes me think that there is something wrong with the implementation, and the application is not able to update the refresh token with the new one whenever it's issued.

    The update on v2.5.0 may have reduced how often token refresh happens, but I don't think it fixed the root cause of what you were having trouble with. All of that, however, is just speculation, and we cannot confirm anything unless you share your implementation of your custom local storage.

    Makes sense. I really just implemented your template code:

    class MySecureStorage extends LocalStorage {
    
      final storage = FlutterSecureStorage();
    
      @override
      Future<void> initialize() async {}
    
      @override
      Future<String?> accessToken() async {
        return storage.read(key: supabasePersistSessionKey);
      }
    
      @override
      Future<bool> hasAccessToken() async {
        return storage.containsKey(key: supabasePersistSessionKey);
      }
    
      @override
      Future<void> persistSession(String persistSessionString) async {
        return storage.write(key: supabasePersistSessionKey, value: persistSessionString);
      }
    
      @override
      Future<void> removePersistedSession() async {
        return storage.delete(key: supabasePersistSessionKey);
      }
    }
    
    Future<void> initSupabase() async {
      await Supabase.initialize(
        url: supabaseURL,
        anonKey: supabaseAnonKey,
        authOptions: FlutterAuthClientOptions(
          localStorage: MySecureStorage(),
        ),
      );
    }

    and because I need to share it with another part of my app I modified it ever so slightly, but it happens with either code:

    class MySecureStorage extends LocalStorage {
    
      final FlutterSecureStorage storage = const FlutterSecureStorage();
    
      @override
      Future<void> initialize() async {}
    
      @override
      Future<String?> accessToken() async {
        print("Attempting to retrieve session data...");
        return storage.read(
            key: supabasePersistSessionKey,
            iOptions: const IOSOptions(
                accountName: keychainService, groupId: keychainSharingGroup));
      }
    
      @override
      Future<bool> hasAccessToken() async {
        print("Checking if session data exists...");
        return storage.containsKey(
            key: supabasePersistSessionKey,
            iOptions: const IOSOptions(
                accountName: keychainService, groupId: keychainSharingGroup));
      }
    
      @override
      Future<void> persistSession(String persistSessionString) async {
        print("Persisting session string: $persistSessionString");
        return storage.write(
            key: supabasePersistSessionKey,
            value: persistSessionString,
            iOptions: const IOSOptions(
                accountName: keychainService, groupId: keychainSharingGroup));
      }
    
      @override
      Future<void> removePersistedSession() async {
        print("Removing session data...");
        return storage.delete(
            key: supabasePersistSessionKey,
            iOptions: const IOSOptions(
                accountName: keychainService, groupId: keychainSharingGroup));
      }
    }
    
  7. micheltucker commented on Apr 23, 2024

    @micheltucker
    Author

    Ok so it must be something with the keychain implementation, as I now used this pub import 'package:shared_preference_app_group/shared_preference_app_group.dart';and extended it like so:

    class MySecureStorage extends LocalStorage {
      @override
      Future<void> initialize() async {
        print("Initializing shared preferences with suite name...");
        await SharedPreferenceAppGroup.setAppGroup(appGroupID);
      }
    
      @override
      Future<String?> accessToken() async {
        print("Attempting to retrieve session data...");
        return SharedPreferenceAppGroup.getString(supabasePersistSessionKey);
      }
    
      @override
      Future<bool> hasAccessToken() async {
        print("Checking if session data exists...");
        var token = await SharedPreferenceAppGroup.getString(supabasePersistSessionKey);
        return token != null;
      }
    
      @override
      Future<void> persistSession(String persistSessionString) async {
        print("Persisting session string: $persistSessionString");
        await SharedPreferenceAppGroup.setString(supabasePersistSessionKey, persistSessionString);
      }
    
      @override
      Future<void> removePersistedSession() async {
        print("Removing session data...");
        await SharedPreferenceAppGroup.remove(supabasePersistSessionKey);
      }
    }
    

    Would be great if somebody could look at the keychain implementation, as it is also the main example for the custom LocalStorage. I spent quite a bit of time trying to figure out where the issue is, but I now believe that the issue actually is with the Keychain/Supabase implementation.

  8. sai-chandra22 commented on May 26, 2025

    @sai-chandra22
       Future<AuthResponse> _callRefreshToken(String refreshToken) async {
         // Refreshing is already in progress
         if (_refreshTokenCompleter != null) {
           _log.finer("Don't call refresh token, already in progress");
           return _refreshTokenCompleter!.future;
         }
    
         try {
           _refreshTokenCompleter = Completer<AuthResponse>();
    @@ -1296,6 +1302,18 @@
           final data = await _refreshAccessToken(refreshToken);
    
           final session = data.session;
    +      // —————— NEW: if we got here, refresh succeeded ——————
           if (session == null) {
             throw AuthSessionMissingException();
           }
    
           _saveSession(session);
           notifyAllSubscribers(AuthChangeEvent.tokenRefreshed);
    
           _refreshTokenCompleter?.complete(data);
           return data;
         } on AuthException catch (error, stack) {
    +      // —————— TREAT specific “already used” as retryable ——————
    +      if (error is AuthApiException && error.code == 'refresh_token_already_used') {
    +        _log.warning(
    +          'Refresh‐token already used; ignoring and retrying on next tick.'
    +        );
    +        // Do NOT remove session or fire SIGNED_OUT
    +        notifyException(error, stack);  
    +        _refreshTokenCompleter?.completeError(error);
    +        rethrow; // so upstream retry logic (in retry()) can pick it up
    +      }
    
           if (error is! AuthRetryableFetchException) {
             // this is a genuine unrecoverable error → sign out
             _removeSession();
             notifyAllSubscribers(AuthChangeEvent.signedOut);
           } else {
             // retryable fetch error (e.g. network hiccup)
             notifyException(error, stack);
           }
    
           _refreshTokenCompleter?.completeError(error);
           rethrow;
         } catch (error, stack) {
           _refreshTokenCompleter?.completeError(error);
           notifyException(error, stack);
           rethrow;
         } finally {
           _refreshTokenCompleter = null;
         }
       }
    
    

    This might resolve the issue, GoTrue by default treats any non‐retryable AuthException during the refresh as “session is dead, sign the user out.” The Supabase service is intentionally rotating your refresh tokens on every use, so if two refreshes race, the second one will come in with an already-used token, get back a 400 refresh_token_already_used, and GoTrue will immediately tear down the session.

    The quickest fix is to treat that specific error as retryable, rather than a hard sign-out.

  9. Vinzent03 commented on May 27, 2025

    @Vinzent03
    Collaborator

    @baptiste-veyrard You shouldn't share a session like that, as a session has only one refresh token and that is invalidated and regenerated for each new access token. So your issue is expected.

    @sai-chandra22 There shouldn't be a case of two access token refreshes to happen simultaneously on the same client. And two different clients shouldn't share the same refresh token. This only happens if two different clients are working with the same refresh token, which should not be the case. But if the client gets a refresh_token_already_used error there is no way to recover the session, so a sign-out is the only way to handle it.

  10. sai-chandra22 commented on May 28, 2025

    @sai-chandra22

    @Vinzent03 , But the cases of two access token is happening, we have give auto refresh capability to supabase sdk by the argument auto refresh to true, and not calling any manual refresh token anywhere still the refresh_token_already_used error and user is logging out

  11. Vinzent03 commented on May 28, 2025

    @Vinzent03
    Collaborator

    @sai-chandra22 Are you even using a custom local storage as the original reason for this issue? May you be affected by #1164? So you are using SharedPreferencesAsync or SharedPreferencesWithCache from the new shared preferences api?

  12. sai-chandra22 commented on May 29, 2025

    @sai-chandra22
      await sb.Supabase.initialize(
        url: ApiKeys.supabaseUrl,
        anonKey: ApiKeys.supabaseAnonKey,
        authOptions: sb.FlutterAuthClientOptions(
          autoRefreshToken: true,
          localStorage:
              CustomSecureStorage(persistSessionKey: LocalStorage.session),
        ),
      );
    
    
    class CustomSecureStorage extends sb.LocalStorage {
      late FlutterSecureStorage _storage;
      final String persistSessionKey;
    
      CustomSecureStorage({required this.persistSessionKey});
    
      @override
      Future<void> initialize() async {
        WidgetsFlutterBinding.ensureInitialized();
        _storage = const FlutterSecureStorage(
          aOptions: AndroidOptions(
            encryptedSharedPreferences: true,
            resetOnError: false,
          ),
          iOptions: IOSOptions(
            accessibility: KeychainAccessibility.first_unlock,
          ),
        );
        debugPrint('🔥 337ssd: Secure storage initialized');
    
        // No need for specific initialization in secure storage
      }
    
      @override
      Future<bool> hasAccessToken() async {
        final exists = await _storage.containsKey(key: persistSessionKey);
        debugPrint('🔍 337ssd: Has access token: $exists');
        return exists;
      }
    
      @override
      Future<String?> accessToken() async {
        final token = await _storage.read(key: persistSessionKey);
        prints('🔑 337ssd: Retrieved access token: $token');
        return token;
      }
    
      @override
      Future<void> persistSession(String persistSessionString) async {
        prints('💾 337ssd: Storing session in secure storage');
        await _storage.write(key: persistSessionKey, value: persistSessionString);
      }
    
      @override
      Future<void> removePersistedSession() async {
        prints('🗑️ 337ssd: Removing session from secure storage');
        await _storage.delete(key: persistSessionKey);
      }
    
      Future<void> clearSecureStorage() async {
        await _storage.delete(key: persistSessionKey);
        debugPrint('🗑️ 337ssd: All secure storage data cleared');
      }
    }
    

    This is what I am using as custom storage, on some devices it is working fine, on some devices the sign out is happening, when app is launched, indicating the same error we discussed above, so that's why I am asking if sharedPreferences can resolve the issue

  13. github-actions commented on Mar 8, 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!

  14. github-actions commented on Apr 19, 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.

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