Invalid access token with flutter loginWithRedirect

Hello,

I’m creating a frontend using Flutter. This frontend will make API calls to my backend. The frontend should work on web, Android and iOS. API calls to my backend should be authenticated with an access token.

As of now, I’m not worried about the backend. I’m trying to get an access token on the frontend side, for flutter web (I haven’tr tried Android or iOS yet). I’m using the sample flutter app from here: https://github.com/auth0/auth0-flutter/tree/main/auth0_flutter

Precisely, I have this code:

  @override
  void initState() {
    super.initState();
    auth0 = widget.auth0 ??
        Auth0(dotenv.env['AUTH0_DOMAIN']!, dotenv.env['AUTH0_CLIENT_ID']!);
    auth0Web =
        Auth0Web(dotenv.env['AUTH0_DOMAIN']!, dotenv.env['AUTH0_CLIENT_ID']!);

    if (kIsWeb) {
      auth0Web.onLoad().then((final credentials) => setState(() {
            _user = credentials?.user;
            print(credentials!.accessToken);
            print("");
            print(credentials?.idToken);
          }));
    }
  }

  Future<void> login() async {
    try {
      if (kIsWeb) {
        return auth0Web.loginWithRedirect(
            redirectUrl: 'http://localhost:8081', audience: 'https://test');
      }

Running this code, I managed to go through the login flow, and id and access tokens are printed. I checked the id token on https://jwt.io/, and it’s valid (it contains all the info) I need. However the access token isn’t valid: “JWT payload isn’t a valid json object”. The data payload is empty.

Could you tell me what I’m doing wrong? I read all the threads on this forum mentioning this issue. I did provide an audience to the loginWithRedirect call: https://test which is the audience of the API that I’ll use as backend. I checked the lenght of the access token being printed, it’s short, so it’s not Flutter cutting it.

Could you give me a hand please?

Hey there @JPFrancoia welcome to the community!

Thanks for bringing this up and for the detailed description :slight_smile:

Super odd! I’m experiencing the same behavior in the sample app FWIW - I’m curious, if you inspect the network tab in the Chrome browser window that is pulled up when running the web portion of the app, do you see 2 separate calls to /oauth/token? The correct token is returned for me in the 1st response, however the token returned in the 2nd response (and subsequently in onLoad) is incorrect:

Keep me posted!

Hi, I’m away at the moment so I can’t check that. What I ended up doing is making a second call to get proper credentials, after the login flow ended:

      creds = await auth0Web.credentials(audience: AUTH0_AUDIENCE);

Then it does work, I get a valid access token

1 Like