sdk-for-flutter icon indicating copy to clipboard operation
sdk-for-flutter copied to clipboard

πŸ› Bug Report: createOAuth2Token Invalid OAuth2 Response. Key and Secret not available

Open Leon0412 opened this issue 5 months ago β€’ 1 comments

πŸ‘Ÿ Reproduction steps

Note: I already reported this error in the Appwrite repo, but since it turned out to be a problem with the Flutter package, I'll recreate the issue here.


await account.createOAuth2Token(
        provider: OAuthProvider.google,
        success: 'appwrite-callback-[project-id]://[host]/v1/auth/oauth2/success/',
        failure: 'appwrite-callback-[project-id]://[host]/v1/auth/oauth2/failure/',
);

Project id and host are set correctly - just anonymized here. Google OAuth is configured correctly in the backend. Google oAuth is configured correctly, also because createOAuth2Session works. The user is also always created in the backend and also has the status β€œVerified email”

πŸ‘ Expected behavior

Automatic redirection back to the app even without succes and failure URL. Valid response so that the result can be processed further and the user can log in.

πŸ‘Ž Actual Behavior

If you trigger this and are redirected back to the app, the user is created in the backend, but i receive this error in Flutter: Error: AppwriteException: , Invalid OAuth2 Response. Key and Secret not available. (500) and in the Docker logs: Deprecated: json_decode(): Passing null to parameter #1 ($json) of type string is deprecated in /usr/src/code/app/controllers/api/account.php on line 1426

If you leave success and failure url empty, you will not be redirected back to the app and you can see in the Docker logs:

Deprecated: json_decode(): Passing null to parameter #1 ($json) of type string is deprecated in /usr/src/code/app/controllers/api/account.php on line 1426
[Error] Timestamp: 2025-06-07T08:26:11+00:00
[Error] Method: GET
[Error] URL: /v1/account
[Error] Type: Appwrite\Extend\Exception
[Error] Message: User (role: guests) missing scope (account)
[Error] File: /usr/src/code/app/controllers/shared/api.php
[Error] Line: 375

🎲 Appwrite version

Different version (specify in environment)

πŸ’» Operating system

Linux

🧱 Your Environment

Self-hosted, Flutter 3.29.3, Dart 3.7.2, Appwrite 1.7.4

πŸ‘€ Have you spent some time to check if this issue has been raised before?

  • [x] I checked and didn't find similar issue

🏒 Have you read the Code of Conduct?

Leon0412 avatar Jun 22 '25 08:06 Leon0412

As already mentioned in the original issue:

I have checked the webAuth() method in your client_io.dart file: ...\appwrite-17.0.1\lib\src\client_io.dart: This awaits key and secret. However, the URL contains only secret and userId - the key is not included here:

[...]
Uri url = Uri.parse(value);
      final key = url.queryParameters['key'];
      final secret = url.queryParameters['secret'];
      if (key == null || secret == null) {
        throw AppwriteException(
          "Invalid OAuth2 Response. Key and Secret not available.",
          500,
        );
      }
[...]

That's why I've rewritten your function locally:

@override
  Future<Map<String, String>> webAuth(Uri url, {String? callbackUrlScheme}) async {
    final result = await FlutterWebAuth2.authenticate(
      url: url.toString(),
      callbackUrlScheme: callbackUrlScheme != null && _customSchemeAllowed
          ? callbackUrlScheme
          : "appwrite-callback-${config['project']!}",
      options: const FlutterWebAuth2Options(
        intentFlags: ephemeralIntentFlags,
        useWebview: false,
      ),
    );

    final uri = Uri.parse(result);
    final userId = uri.queryParameters['userId']; // instead of 'key'
    final secret = uri.queryParameters['secret'];

    if (userId == null || secret == null) {
      throw AppwriteException(
        "Invalid OAuth2 Response. User ID or Secret not available.",
        500,
      );
    }

    Cookie cookie = Cookie(userId, secret); // 'userId' instead of 'key'
    cookie.domain = Uri.parse(_endPoint).host;
    cookie.httpOnly = true;
    cookie.path = '/';
    List<Cookie> cookies = [cookie];
    await init();
    _cookieJar.saveFromResponse(Uri.parse(_endPoint), cookies);

    return {'userId': userId, 'secret': secret};
  }

Note that I have changed the method so that userId and secret are returned so that i can then easily execute account.createSession():

await account.createSession(
        userId: result['userId'],
        secret: result['secret'],
      );

With these changes it now works for me. The user is created, the session is also created and the user can be successfully logged in. Nevertheless, the success and failure parameters must still be specified in account.createOAuth2Token() so that the app opens again.

It works perfectly in the emulator. On a real device (in this case Samsung S23 Ultra), however, only a loading animation is displayed after selecting an account to log in. So the account selection is grayed out and the loading animation runs continuously. The app receives the data in the background, but is not opened. However, when I close the browser, I am logged in, but I have a solution here too: To solve the problem, I have to remove the android:taskAffinity=β€œβ€ in the AndroidManifest.xml. entry. Then it also works on the real physical device.


The error message Invalid OAuth2 Response. Key and Secret not available comes from the above-mentioned file from your Flutter package. However, after the changes mentioned above, I no longer receive any error messages.


Let me know if I can do anything more or if you need more information.

Leon0412 avatar Jun 22 '25 08:06 Leon0412

@Leon0412 ah yes. It looks like the webAuth method is designed only to be used with createOAuth2Session rather than both createOAuth2Session and createOAuth2Token. We'll discuss internally how to approach this.

stnguyen90 avatar Jun 27 '25 18:06 stnguyen90

hi @stnguyen90 i am interested to work on this i am noe here can you guide me how i can contribute to it

mdex-geek avatar Jul 25 '25 17:07 mdex-geek

@mdex-geek take a look at our sdk generator's contributing guide here - https://github.com/appwrite/sdk-generator/blob/master/CONTRIBUTING.md

ChiragAgg5k avatar Sep 29 '25 04:09 ChiragAgg5k