fluttergmail-apigoogle-developers-consoleclientid

insufficient Scope when trying to access gmail


I have been trying to access gmail in my flutter code. And after so many attempts I arrive at the insufficient scope error. Here is the code.

final GoogleSignIn _googleSignIn = GoogleSignIn();

  Future<void> authenticateAndFetchEmails() async {
    try {
      // Sign in the user
      final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();

      // Retrieve authentication credentials
      final GoogleSignInAuthentication googleAuth = await googleUser!.authentication;

      // Use the access token for authorization
      final accessToken = googleAuth.accessToken!;
      print(accessToken);
      // Create authenticated client
      final client = authenticatedClient(
        http.Client(),
        AccessCredentials(
          AccessToken(
            'Bearer',
            accessToken,
            DateTime.now().toUtc().add(Duration(hours: 1)), // Example expiry
          ),
          null, // No refresh token provided
          ['https://www.googleapis.com/auth/gmail.readonly'],
        ),
      );

      final gmailApi = gmail.GmailApi(client);
      final response = await gmailApi.users.messages.list('me');
      final messages = response.messages ?? [];

      for (var message in messages) {
        final msg = await gmailApi.users.messages.get('me', message.id!);
        final snippet = msg.snippet!;

        if (snippet.contains('Debit') ||
            snippet.contains('Account Name') ||
            snippet.contains('Description')) {
          print('Found email: ${msg.payload!.headers!.firstWhere((header) => header.name == 'Subject').value}');
        }
      }
    } catch (e) {
      print('Failed to authenticate or fetch emails: $e');
    }
  }

and this is the error I got;

 Failed to authenticate or fetch emails: Access was denied (www-authenticate header was: Bearer realm="https://accounts.google.com/", error="insufficient_scope", scope="https://mail.google.com/ https://mail.google.com/mail/feed/atom https://mail.google.com https://mail.google.com/mail/feed/atom/ https://mail.google.com/mail https://mail.google.com/mail/ http://mail.google.com/ http://mail.google.com https://www.googleapis.com/auth/gmail.modify https://www.googleapis.com/auth/gmail.readonly https://www.googleapis.com/auth/gmail.metadata").

I have tried pretty much everything I can think of. I have set the scope of my clientId to gmail.read only, The email I am using to test is a part of the test users in the OAuth consent screen. I have Enabled the Gmail Api in my Google console. There is something I am missing. If anyone has an idea what it is that would make my day!


Solution

  • if you check the documentation for user messages list

    you will notice that it requires one of the following scopes

    enter image description here

    As does user messages get

    If you are getting that error message then your user has not authorized you to access their Gmail account with one of those scopes.

    Make sure that the access token was created when you requested the appropriate scope.

    Maybe this Authenticate the user with the required scopes