Flutter: ERR_NAME_NOT_RESOLVED when backend redirects with a custom scheme

1.1k Views Asked by At

I am trying to login via Twitch and, to do that I am using https://pub.dev/packages/url_launcher and https://pub.dev/packages/uni_links. The code works well on iOS, but not on Android.

The process is:

  • Click on "Sign in with Twitch"
  • Opens a browser via launchUrl(_url)
  • Accept authorization of Twitch popup
  • Redirects to the callback of my backend server
  • Backend: Create/Retrieve the user
  • Backend: Returns a 307 HTTP with url: customscheme://auth/twitch?access_token=...
  • Listens the Deep Link: Close the browser and stores the token in the device

On Android, when my browser tries to redirect with my customscheme, the device browser returns an error:

Webpage not available

The webpage at
http://customscheme//auth/twitch?access_token=XXX
could not be loaded because:

net::ERR_NAME_NOT_RESOLVED

The customscheme is replaced by mine, and it works when I test it with the command:

adb shell am start -a android.intent.action.VIEW -c android.intent.category.BROWSABLE -d "customscheme://auth/twitch".

So it seems it does not understand the custom scheme from the webview, and handle it like a simple HTTP url.

Here is my code:

  void logWithTwitch() async {
    assert(dotenv.env['TWITCH_CLIENT_ID'] != null);
    assert(dotenv.env['TWITCH_REDIRECT_URI'] != null);

    final String twitchClientId = dotenv.env['TWITCH_CLIENT_ID']!;
    final String twitchRedirectUri = dotenv.env['TWITCH_REDIRECT_URI']!;
    final List<String> scopes = [
      'user:read:email',
    ];
    final Uri _url = Uri(
        scheme: 'https',
        host: 'id.twitch.tv',
        path: 'oauth2/authorize',
        queryParameters: {
          'client_id': twitchClientId,
          'redirect_uri': twitchRedirectUri,
          'response_type': 'code',
          'scope': scopes.join(' '),
          'force_verify': 'true',
        });

    if (await canLaunchUrl(_url)) {
      await launchUrl(_url);
    } else {
      print('cannot open url');
    }
  }

...

_sub = linkStream.listen((String? link) {
    if (link == null) {
        return;
    }

    final _url = Uri.parse(link);
    if (_url.host == 'auth' && _url.path == '/twitch') {
        closeInAppWebView();
        // Handle Authentication
    }
}, onError: (err) {
    // Handle exception by warning the user their action did not succeed
});

Thank you for your help!

1

There are 1 best solutions below

1
On

I got the same problem after updating my project to the newest version. Seems like the problem comes from launching the webview directly in the flutter app. found a workaround for it: use the launchmode option in the launchUrlString Function: launchUrlString(_url,mode: launchMode.externalApplication)