#[SOLVED] AppwriteException: Invalid OAuth2 Response. Key and Secret not available. (500)

68 messages · Page 1 of 1 (latest)

light steeple
#

Hello Appwriter,

i'm creating an OAuth Login with Apple, i have configure everything on my Apple Developer Account and in my Appwrite Console,
When i Login with Apple, the user Full name and Email is Created in the Appwrite Cloud Cosole (Auth)

I dont know what's wrong in my code, i keep getting this error response:

GOING TO ROUTE /App
flutter: #0      ClientIO.webAuth.<anonymous closure> (package:appwrite/src/client_io.dart:371:9)
flutter: <asynchronous suspension>
flutter: #1      AppwriteService.loginWithOAuth (package:prayerbuddynewlook/services/appwrite_service.dart:88:7)
flutter: <asynchronous suspension>
flutter: #2      AuthController.loginWithOAuth (package:prayerbuddynewlook/controllers/auth_controller.dart:41:7)
flutter: <asynchronous suspension>```

**here is my Appwrite Services:**

```Future<void> loginWithOAuth(String provider) async {
    try {
      final redirectUri = 'https://prayerbuddyapp.joons-me.com';
      await account.createOAuth2Session(
        provider: _mapProvider(provider), // 'facebook', 'google', 'apple'
        success: '$redirectUri/loginSuccess',
        failure: '$redirectUri/loginFail',
      );
      _currentUserId = null;
    } catch (e, s) {
      debugPrint('OAuth login error: $e\n$s');
      throw Exception('OAuth login failed');
    }
  }


OAuthProvider _mapProvider(String name) {
  switch (name.toLowerCase()) {
    case 'google':
      return OAuthProvider.google;
    case 'facebook':
      return OAuthProvider.facebook;
    case 'apple':
      return OAuthProvider.apple;
    // add more if you need them
    default:
      throw Exception('Unknown provider $name');
  }```
#

Here is my Controller

    isLoading.value = true;
    try {
      await _appwrite.loginWithOAuth(provider);
      currentUserId.value = await _appwrite.getCurrentUserId();

      print('currentUserId ${currentUserId.value}');
      print("LoginSuccess Controller");
      Get.offAll(() => const App(login: true));
    } catch (e) {
      Get.snackbar('Error', e.toString());
    } finally {
      isLoading.value = false;
    }
  }```
#

Here is my DeepLink

   Future<void> initDeepLinks() async {
    // print('Deep-Initial');
    // Check initial link if app was in cold state (terminated)
    final appLink = await _appLinks.getInitialLink();
    if (appLink != null) {
      var uri = Uri.parse(appLink.toString());
      var pathName = uri.pathSegments[0];

      if (pathName == 'loginSuccess') {
        print("LoginSuccess Deeplink");
        Get.to(() => const App(login: true));
      } else if (pathName == 'loginFail') {
        print("LoginFail Deeplink");
        Get.to(() => const Login());
      } else if (pathName == 'series') {
        Get.to(() => const App(login: true));
      } else if (pathName == 'messageSeries') {
        var seriesId = uri.queryParameters["seriesId"];
        var vidId = uri.queryParameters["vidId"];
        // Get.to(() => WatchVideoDeepLink(seriesId: seriesId.toString(), vidId: vidId.toString()));
      }
      //Get.to(() => const Login());
    }
  }

each and everytime LoginSuccess Deeplink is printed out, but the error output above is still be outputted

light steeple
#

AppwriteException: Invalid OAuth2 Response. Key and Secret not available. (500)

light steeple
#

hello, is there any suggestion on what might be wrong <@&634618551491100692>

lime slate
light steeple
#

Okay, thanks for the correction, but i have literally followed every article on setting it up on Apple,
I have my service id, team id, key id and .p8 file.

The user is been created inside the auth but only one user though, even if i try other apple account others will not be created until i removed the already created user before that one can be inserted.

e.g:
i have 3 apple account [email protected], [email protected], [email protected]
when i signIn with apple with [email protected], that user will be inserted inside the auth of appwrite console,

so when i try to signin now with [email protected] or [email protected], these user will not be created inside the auth, until i delete [email protected] or [email protected] before the subsequent user from apple can be created inside the auth.

even though the user is created inside the auth, this issue still persist AppwriteException: Invalid OAuth2 Response. Key and Secret not available. (500)

proven condor
#

did you set those in your console?
Why doesn't your deep link success do account.createSession? I am pretty sure the return URL has a token in it, but I could be wrong, I write my own oauth stuff usually

light steeple
#

Yes, i set those in my console

proven condor
#

so then the app is registered to the bundle, and you have a servide ID?

lime slate
light steeple
#

yes

proven condor
#

hm, are you reinitializing a client instance? Are you using Riverpod providers? Are they keepalive providers? I also can't really tell your code apart overall like the flow, if you could organize it a bit better into one or two places that would help a bit. Is this self hosted or cloud?

proven condor
#

If you're not using Riverpod in flutter for instance, I'm not sure how one would keep that state consistent

light steeple
#

i'm using GetX

proven condor
#

man people who make a package called 'get' can suck my butt

#

what a terrible and meaningless name

#

anyways

proven condor
#

So I've never used this, I'm not sure how it works, but what I can say, is that the OAuth for Apple should be the same as the others. Within reason. I would log the full Deep Link URL

#

and then, hm, personally, I would make an OAuth function, to solve this, because I can't see what's going on and that bothers me

#

but it's hard to tell. That seems like an error I'd expect from the SDK if your bundle identifier was wrong in the Appwrite platform configuration like, who's allowed to make requests

#

cause the server-request is working, seemingly, if it's making the user

light steeple
proven condor
#

so it's either losing the context of Appwrite's SDK setting the access token due to Get discarding it, or something else, seemingly

#

my guess is the first, cause I know with Riverpod providers they're built on Flutters engine

#

this guy seems to have said, "I don't like Flutter, I want to make my own flutter" and just done away with like, most of what I thought was the point

#

the widget tree and intentional context may be annoying but they were a large part of what kept it safe, I felt

proven condor
#

I would highly recommend using Riverpod v3

#

I know it's not a solution, but, from what I've been reading GetX seems to try to solve a problem nobody wanted them to, but for anything scalable it seems to have poor unit tests and test support in general, limited scope of different state, tightly coupled to controllers

light steeple
#

ok

proven condor
#

like, if you use email password, does that work reliably?

#

can you close the app, or rebuild it, and then log in the same?

#

or rather, stay logged in

light steeple
#

yes, i can login via email and password, and if i login via email and password, i stay logged in till i had to logout

#

login via email and password works very well

proven condor
#

interesting

light steeple
#

yes

light steeple
#

instead of creatOauthSession i now used createOAuth2Token

  Future<void> loginWithOAuth(String provider) async {
    final redirectUri = 'https://prayerbuddyapp.joons-me.com';
    try {
      final session = await account.createOAuth2Token(
        provider: _mapProvider(provider), // 'facebook', 'google', 'apple'
        success: '$redirectUri/loginSuccess',
        failure: '$redirectUri/loginFail',
      );

      final authUrl = session.toMap()['url'] as String;
      await launchUrl(Uri.parse(authUrl));
    } catch (e, s) {
      debugPrint('OAuth login error: $e\n$s');
      throw Exception('OAuth login failed');
    }
  }```

i could now get the userId and the secret via my deeplink but this error **flutter: OAuth login error: AppwriteException: , Invalid OAuth2 Response. Key and Secret not available. (500) still persist**

*update Deeplink Code*
```print("Deeplink uriValue $uriValue");
        // print('Deep-Warm');
        var pathName = uriValue.pathSegments[0];

        if (pathName == 'loginSuccess') {
          final userId = uriValue.queryParameters['userId'];
          final secret = uriValue.queryParameters['secret'];
          if (userId != null && secret != null) {
            // Step 4: create a session manually
            print('UserID ${userId}');
            print('secret ${secret}');

            await AppwriteService().account.createSession(userId: userId, secret: secret);
            final user = await AppwriteService().account.get();
            debugPrint('Logged in as ${user.name}');

            print("LoginSuccess uriValue");
            Get.to(() => const App(login: true));
          }
        }```

The Print Out
flutter: Deeplink uriValue https://prayerbuddyapp.joons-me.com/loginSuccess?secret=3bc295594e442bf3ee739b3cbe0dec7a480739c2636cacb0b781dcf7bc86d0e9&userId=68d1d41109eeb0c30384#
flutter: UserID 68d1d41109eeb0c30384
flutter: secret 3bc295594e442bf3ee739b3cbe0dec7a480739c2636cacb0b781dcf7bc86d0e9
#

@proven condor

light steeple
#

helloo

solid owl
#

Can you try use creatOauthSession again and remove the success and failure URL and try again?

light steeple
#

okay

#

using creatOauthSession without passing the success and failure params, this is what i got

flutter: #0      ClientMixin.prepareResponse (package:appwrite/src/client_mixin.dart:90:9)
flutter: #1      ClientIO.call (package:appwrite/src/client_io.dart:415:14)
flutter: <asynchronous suspension>
flutter: #2      Account.get (package:appwrite/services/account.dart:16:17)
flutter: <asynchronous suspension>
flutter: #3      AppwriteService.loginWithOAuth (package:prayerbuddynewlook/services/appwrite_service.dart:99:20)
flutter: <asynchronous suspension>
flutter: #4      AuthController.loginWithOAuth (package:prayerbuddynewlook/controllers/auth_controller.dart:41:7)
flutter: <asynchronous suspension>
flutter:```
solid owl
#

I'm asking to the core team for help, as there is a known issue in flutter and I'm not sure if this was solved or not. What flutter sdk version are you using?

light steeple
#
Flutter 3.35.3 • channel stable • https://github.com/flutter/flutter.git
Framework • revision a402d9a437 (3 weeks ago) • 2025-09-03 14:54:31 -0700
Engine • hash 672c59cfa87c8070c20ba2cd1a6c2a1baf5cf08b (revision ddf47dd3ff) (19 days ago) • 2025-09-03 20:02:13.000Z
Tools • Dart 3.9.2 • DevTools 2.48.0
(base) zionnite@Nosakhares-MacBook-Air android % 
#

wow, so this is appwrite bug

solid owl
#

I'm just confirming that, can you post the Appwrite SDK version too?

light steeple
#

appwrite: ^19.0.0

light steeple
#

what the appwrite core team saying regarding this @solid owl

light steeple
#

sitll no update from appwrite team regarding this

severe crown
light steeple
#

even on a pro plan bro, the support is still like this bro

lime slate
light steeple
#

so, whats appwrite team saying regarding this issues

solid pine
#

do you init the APWClient before calling Get.to ?
for the oAuth, it is a redirect, so the app will be back into an inital state. The APWClient persist the token within a cookie.
Based on your code it looks like you just try to create a new client within your deepLink router.
So try to init the client with the start of the app, in this way it should get

also the flow looks wired.
when you call the createOath session, you should not call getCurrentUser, because at this stage you don't have a user, that explains the error.

when the callback is coming, and a fresh state of the app gets init, you should not depend on the callback url to know if the user is logged in or not.
the callback url should either guide the user to main, or to error.
and on main your usual logic should happen to verify if the user is logged in, if not redirect to login, if so, and there is a deeplink, redirect to deep link

light steeple
#

thanks for your response, really what is happening is strange, now is started working without me having to pass any params to the creatOauthSession()

User is being created in auth tab,
user detail is being created in the profile table.

but the issue now is that i randomly get OAuth login error: AppwriteException: general_unauthorized_scope, User (role: guests) missing scopes (["account"]) (401)

the behaviour is random, it work a minute and it won't work again.

#

Appwrite Service

    try {
      await account.createOAuth2Session(
        provider: _mapProvider(provider),
      );

      var user = await account.get();
      String fullName = user.name ?? '';
      String username;

      if (fullName.trim().isEmpty) {
        fullName = _deriveNameFromEmail(user.email ?? '');
        username = fullName.split(' ').first;

        await account.updateName(name: fullName);

        // Refresh the user object to reflect the change
        user = await account.get();
      } else {
        username = fullName.split(' ').first;
      }

      await functions.createExecution(
        functionId: '68cf73910030dc814371',
        body: jsonEncode({
          'userId': user.$id,
          'username': user.$id,
          'fullName': fullName,
        }),
      );
    } catch (e, s) {
      debugPrint('OAuth login error: $e\n$s');
      throw Exception('OAuth login failed');
    }
  }```
#

Controller

Future<void> loginWithOAuth(String provider) async {
    isLoading.value = true;
    try {
      await _appwrite.loginWithOAuth(provider);
      Get.offAll(() => const App(login: true));
    } catch (e) {
      print('Error ${e.toString()}');
      Get.snackbar('Error', e.toString());
    } finally {
      isLoading.value = false;
    }
  }
#

My function permission is ANY

light steeple
#

funny thing happen,
i did do anything to the code, everything its working