Git Product home page Git Product logo

thexxturboxx / flutter_web_auth_2 Goto Github PK

View Code? Open in Web Editor NEW

This project forked from linusu/flutter_web_auth

47.0 4.0 44.0 12.03 MB

Flutter plugin for authenticating a user with a web service

Home Page: https://pub.dev/packages/flutter_web_auth_2

License: MIT License

Kotlin 3.31% Ruby 4.71% Swift 12.25% Objective-C 0.43% Dart 32.18% HTML 2.34% CMake 19.92% C++ 23.37% C 1.49%
auth flutter web hacktoberfest oauth oauth1 oauth2 sfauthenticationsession flutter-plugin dart

flutter_web_auth_2's Introduction

Web Auth 2 for Flutter

This project is a continuation of flutter_web_auth by Linus Unnebäck with many new features and bug fixes.

melos

A Flutter plugin for authenticating a user with a web service, even if the web service is run by a third party. Most commonly used with OAuth2, but can be used with any web flow that can redirect to a custom scheme.

In the background, this plugin uses ASWebAuthenticationSession on iOS 12+ and macOS 10.15+, SFAuthenticationSession on iOS 11, Chrome Custom Tabs on Android and opens a new window on Web. You can build it with iOS 8+, but it is currently only supported by iOS 11 or higher.

Usage

Add the following snippet to your pubspec.yaml and follow the Setup guide:

dependencies:
  flutter_web_auth_2: ^4.0.0-alpha.0

To authenticate against your own custom site:

import 'package:flutter_web_auth_2/flutter_web_auth_2.dart';

// Present the dialog to the user
final result = await FlutterWebAuth2.authenticate(url: "https://my-custom-app.com/connect", callbackUrlScheme: "my-custom-app");

// Extract token from resulting url
final token = Uri.parse(result).queryParameters['token'];

To authenticate the user using Google's OAuth2:

import 'package:flutter_web_auth_2/flutter_web_auth_2.dart';

import 'dart:convert' show jsonDecode;
import 'package:http/http.dart' as http;

// App specific variables
final googleClientId = 'XXXXXXXXXXXX-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com';
final callbackUrlScheme = 'com.googleusercontent.apps.XXXXXXXXXXXX-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

// Construct the url
final url = Uri.https('accounts.google.com', '/o/oauth2/v2/auth', {
  'response_type': 'code',
  'client_id': googleClientId,
  'redirect_uri': '$callbackUrlScheme:/',
  'scope': 'email',
});

// Present the dialog to the user
final result = await FlutterWebAuth2.authenticate(url: url.toString(), callbackUrlScheme: callbackUrlScheme);

// Extract code from resulting url
final code = Uri.parse(result).queryParameters['code'];

// Construct an Uri to Google's oauth2 endpoint
final url = Uri.https('www.googleapis.com', 'oauth2/v4/token');

// Use this code to get an access token
final response = await http.post(url, body: {
  'client_id': googleClientId,
  'redirect_uri': '$callbackUrlScheme:/',
  'grant_type': 'authorization_code',
  'code': code,
});

// Get the access token from the response
final accessToken = jsonDecode(response.body)['access_token'] as String;

Note: To use multiple scopes with Google, you need to encode them as a single string, separated by spaces. For example, scope: 'email https://www.googleapis.com/auth/userinfo.profile'. Here is a list of all supported scopes.

Upgrading to 4.x

Version 4.0.0 introduced a new approach for Linux and Windows to authenticate users - using Webview APIs. Hence, you only need to change your code if you are targeting Linux or Windows. If you are fine with still using the old version, here is what you need to change:

  • Pass useWebview: false into the options of your call to authenticate, like so:
    final result = await FlutterWebAuth2.authenticate(
      url: url,
      callbackUrlScheme: 'foobar',
      options: const FlutterWebAuth2Options(useWebview: false),
    );

If you want to use the new approach (default behaviour!), you need to do a bit more:

  • Follow the "Getting started" guide of desktop_webview_window
  • Make sure that your users know about the new requirements, as described here

Upgrading to 3.x

Version 3.0.0 featured a huge refactor which made it possible to maintain even more configuration possibilities. Even platform-specific ones! If you want to upgrade, you need to do the following:

  • Follow the [Setup] within this README again for your platform and do it from scratch (there might be changes!)
  • Dart SDK constraints have been updated to >=2.15.0.
  • The configuration parameters have been removed from the authenticate function. Now, you have to pass a FlutterWebAuth2Options object with those options in it instead:
    • contextArgs: This is now called windowName within FlutterWebAuth2Options.
    • redirectOriginOverride: This is now called debugOrigin within FlutterWebAuth2Options.
    • preferEphemeral: This has been split into the two named parameters preferEphemeral (for iOS and MacOS) and intentFlags (for Android) within FlutterWebAuth2Options. The former works exactly the same. However, if you want the old behaviour using preferEphemeral on Android, use the ephemeralIntentFlags constant as value for intentFlags.

Upgrading from flutter_web_auth

If you used flutter_web_auth correctly (and without extra hackage) before, it should be sufficient to replace the following strings everywhere (yes, also in AndroidManifest.xml for example):

  • FlutterWebAuth -> FlutterWebAuth2
  • flutter_web_auth -> flutter_web_auth_2

If you are using versions >= 3.0.0, you also need to follow the migration guide(s) above!

If you are still unsure or something is not working as well as before, please open a new issue.

Setup

Setup is the same as for any Flutter plugin, with the following caveats:

Android

In order to capture the callback url, the following activity needs to be added to your AndroidManifest.xml. Be sure to replace YOUR_CALLBACK_URL_SCHEME_HERE with your actual callback url scheme.

<manifest>
  <application>

    <activity
      android:name="com.linusu.flutter_web_auth_2.CallbackActivity"
      android:exported="true">
      <intent-filter android:label="flutter_web_auth_2">
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="YOUR_CALLBACK_URL_SCHEME_HERE" />
      </intent-filter>
    </activity>

  </application>
</manifest>

If you are using http or https as your callback scheme, you also need to specify a host etc. See c:geo as an example for this.

iOS

For "normal" authentication, just use this library as usual; there is nothing special to do!

To authenticate using Universal Links on iOS, use https as the provided callbackUrlScheme:

final result = await FlutterWebAuth2.authenticate(url: "https://my-custom-app.com/connect", callbackUrlScheme: "https");

Web

On the Web platform, an endpoint must be created that captures the callback URL and sends it to the application using the JavaScript postMessage() method. In the ./web folder of the project, create an HTML file named, e.g. auth.html with content:

<!DOCTYPE html>
<title>Authentication complete</title>
<p>Authentication is complete. If this does not happen automatically, please close the window.</p>
<script>
  function postAuthenticationMessage() {
    const message = {
      'flutter-web-auth-2': window.location.href
    };

    if (window.opener) {
      window.opener.postMessage(message, window.location.origin);
      window.close();
    } else if (window.parent && window.parent !== window) {
      window.parent.postMessage(message, window.location.origin);
    } else {
      localStorage.setItem('flutter-web-auth-2', window.location.href);
      window.close();
    }
  }

  postAuthenticationMessage();
</script>

This HTML file is designed to handle both traditional window-based and iframe-based authentication flows. The JavaScript code checks the context and sends the authentication response accordingly.

The redirect URL passed to the authentication service must be the same as the URL the application is running on (schema, host, port if necessary) and the path must point to the generated HTML file, in this case /auth.html. The callbackUrlScheme parameter of the authenticate() method does not take this into account, so it is possible to use a schema for native platforms in the code.

For the Sign in with Apple in web_message response mode, postMessage from https://appleid.apple.com is also captured, and the authorisation object is returned as a URL fragment encoded as a query string (for compatibility with other providers).

Additional parameters for the URL open call can be passed in the authenticate function using the windowName parameter from the options. The silentAuth parameter can be used to enable silent authentication within a hidden iframe, rather than opening a new window or tab. This is particularly useful for scenarios where a full-page redirect is not desirable. Setting this parameter to true allows for a seamless user experience by performing authentication in the background, making it ideal for token refreshes or maintaining user sessions without requiring explicit interaction from the user.

Windows and Linux

When using useWebview: false, there is a limitation that the callback URL scheme must start with http://localhost:{port}.

When specifying useWebview: true (which is the default behaviour), you need to make sure to follow desktop_webview_window's guide. Also be aware that your users might need to install a Webview API (which is preinstalled on Windows 11 and some Windows 10 and Linux installations). For details, see also desktop_webview_window's guide above.

Troubleshooting

When you use this package for the first time, you may experience some problems. These are some of the most common solutions:

General troubleshooting steps

  1. Stop the application if it is running.
  2. Run the following commands:
    • flutter clean
    • flutter pub upgrade
  3. Rerun the application after executing the above commands. Sometimes, they work wonders!

Troubleshooting callbackUrlScheme

  • callbackUrlScheme must be a valid schema string or else this library won't work
  • A valid RFC 3986 URL scheme must consist of "a letter and followed by any combination of letters, digits, plus "+", period ".", or hyphen "-"
  • scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
  • This means you can not use underscore "_", space " " or uppercase "ABCDEF...". It must also not start with a number. See RFC3986#page-17
  • Examples of VALID callbackUrlSchemes are callback-scheme, another.scheme, examplescheme
  • Examples of INVALID callbackUrlSchemes are callback_scheme,1another.scheme, exampleScheme

Troubleshooting Flutter App

  • You have to tell the FlutterWebAuth2.authenticate function what your callbackUrlScheme is.

  • Example: If your callbackUrlScheme is valid-callback-scheme, your dart code will look like

    import 'package:flutter_web_auth_2/flutter_web_auth_2.dart';
    
    // Present the dialog to the user
    final result = await FlutterWebAuth2.authenticate(url: "https://my-custom-app.com/connect", callbackUrlScheme: "valid-callback-scheme");

Troubleshooting Android

  • You will need to update your AndroidManifest.xml to include the com.linusu.flutter_web_auth_2.CallbackActivity activity, something like

    <manifest>
      <application>
    
        <!-- add the com.linusu.flutter_web_auth_2.CallbackActivity activity -->
        <activity
          android:name="com.linusu.flutter_web_auth_2.CallbackActivity"
          android:exported="true">
          <intent-filter android:label="flutter_web_auth_2">
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="YOUR_CALLBACK_URL_SCHEME_HERE" />
          </intent-filter>
        </activity>
    
      </application>
    </manifest>
  • Example of a valid AndroidManifest.xml with VALID callbackUrlScheme. In the example below our callbackUrlScheme is valid-callback-scheme.

    <manifest>
      <application>
        <activity
          android:name="com.linusu.flutter_web_auth_2.CallbackActivity"
          android:exported="true">
          <intent-filter android:label="flutter_web_auth_2">
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="valid-callback-scheme" />
          </intent-filter>
        </activity>
    
      </application>
    </manifest>
  • If you are targeting S+ (SDK version 31 and above) you need to provide an explicit value for android:exported. If you followed earlier installation instructions, this was not included. Make sure that you add android:exported="true" to the com.linusu.flutter_web_auth.CallbackActivity activity in your AndroidManifest.xml file.

    - <activity android:name="com.linusu.flutter_web_auth_2.CallbackActivity">
    + <activity
    +   android:name="com.linusu.flutter_web_auth_2.CallbackActivity"
    +   android:exported="true">
  • If you want to have a callback URL with http or https scheme, you also need to specify a host etc. See c:geo as an example for this.

Troubleshooting OAuth redirects

  • Your OAuth Provider must redirect to the valid callbackUrlScheme + ://. This mean if your callbackUrlScheme is validscheme, your OAuth Provider must redirect to validscheme://
  • Example with PHP:
    <?php
    
    header("Location: validscheme://?data1=value1&data2=value2");

Troubleshooting HTML redirects

  • If you are using HTML hyperlinks, it must be a valid callbackUrlScheme + ://. This means that if your callbackUrlScheme is customappname, your HTML hyperlink should be customappname://

  • Example with HTML:

    <a href="customappname://?data1=value1&data2=value2">Go Back to App</a>

Troubleshooting passing data to app

  • You can pass data back to your app by adding GET query parameters. This is done by adding a name=value type of data after your callbackUrlScheme + :// + ?

  • Example to pass access-token to your app:

    my-callback-schema://?access-token=jdu9292s
    
  • You can pass multiple dates by concatenating them with &:

    my-callback-schema://?data1=value1&data2=value2
    
  • Example to pass access-token and user_id to your app:

    my-callback-schema://?access-token=jdu9292s&user_id=23
    
  • You can get the data in your app through Uri.parse(result).queryParameters:

    // Present the dialog to the user
    final result = await FlutterWebAuth2.authenticate(url: "https://my-custom-app.com/connect", callbackUrlScheme: "valid-callback-scheme");
    // Extract token from resulting url
    String accessToken = Uri.parse(result).queryParameters['access-token'];
    String userId = Uri.parse(result).queryParameters['user_id'];

Cannot open keyboard on iOS

This seems to be a bug in ASWebAuthenticationSession and no workarounds have been found yet. Please see issue #120 for more info.

Error on macOS if Chrome is default browser

This seems to be a bug in ASWebAuthenticationSession and no workarounds have been found yet. Please see issue #136 for more info.

flutter_web_auth_2's People

Contributors

abdelaziz-mahdy avatar adam-langley avatar coreysprague avatar czepiec avatar devmvk avatar doldrums avatar harrowmykel avatar humzakt avatar ii11ii avatar jon-salmon avatar josmo avatar jothomps avatar junying1 avatar knupper avatar linusu avatar lvinci avatar mino5531 avatar mreichelt avatar niggelgame avatar noga-dev avatar nonameden avatar poster983 avatar prasadsunny1 avatar rexios80 avatar rundfunk47 avatar sallaben avatar thexxturboxx avatar timshadel avatar will5 avatar xvrick avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

flutter_web_auth_2's Issues

Allow to configure window `open` on web

Is your feature request related to a problem? Please describe.

When using flutter_web_auth_2 on web, it is not possible to configure how the auth window will open.

Describe the solution you'd like

I would like to configure the window.open call based on a custom configuration.
For example I would like to use a popup instead of a new window.

Describe alternatives you've considered

Currently there are no configuration options.
A custom implementation on a fork is the only possible option.

Additional context

This part


should be more configurable, so that e.g.

context.callMethod('open', [url, "popup", "popup=true"]);

can be achieved.

Upgrading to oauth2_client 3.0.0 (using flutter_web_auth_2) fails

Description

When upgrading oauth2_client to 3.0.0 that introduces use of flutter_web_auth_2, I get a build error that looks related to making the plugin dependant on kotlin-gradle-plugin 1.7.10:

Running Gradle task 'assembleRelease'...                        

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':flutter_web_auth_2'.
> Could not resolve all artifacts for configuration ':flutter_web_auth_2:classpath'.
   > Could not resolve org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.10.
     Required by:
         project :flutter_web_auth_2
      > The consumer was configured to find a runtime of a component compatible with Java 13, packaged as a jar, and its dependencies declared externally. However we cannot choose between the following variants of org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.10:
          - gradle70JavadocElements
          - gradle70RuntimeElements
          - gradle70SourcesElements
          - javadocElements
          - runtimeElementsWithFixedAttribute
          - sourcesElements
        All of them match the consumer attributes:
          - Variant 'gradle70JavadocElements' capability org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.10 declares a runtime of a component, and its dependencies declared externally:
              - Unmatched attributes:
                  - Provides documentation but the consumer didn't ask for it
                  - Provides javadocs but the consumer didn't ask for it
                  - Doesn't say anything about its target Java version (required compatibility with Java 13)
                  - Doesn't say anything about its elements (required them packaged as a jar)
                  - Provides attribute 'org.gradle.plugin.api-version' with value '7.0' but the consumer didn't ask for it
                  - Provides release status but the consumer didn't ask for it
          - Variant 'gradle70RuntimeElements' capability org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.10 declares a runtime of a component compatible with Java 8, packaged as a jar, and its dependencies declared externally:
              - Unmatched attributes:
                  - Provides a library but the consumer didn't ask for it
                  - Provides attribute 'org.gradle.jvm.environment' with value 'standard-jvm' but the consumer didn't ask for it
                  - Provides attribute 'org.gradle.plugin.api-version' with value '7.0' but the consumer didn't ask for it
                  - Provides release status but the consumer didn't ask for it
          - Variant 'gradle70SourcesElements' capability org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.10 declares a runtime of a component, and its dependencies declared externally:
              - Unmatched attributes:
                  - Provides documentation but the consumer didn't ask for it
                  - Provides sources but the consumer didn't ask for it
                  - Doesn't say anything about its target Java version (required compatibility with Java 13)
                  - Doesn't say anything about its elements (required them packaged as a jar)
                  - Provides attribute 'org.gradle.plugin.api-version' with value '7.0' but the consumer didn't ask for it
                  - Provides release status but the consumer didn't ask for it
          - Variant 'javadocElements' capability org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.10 declares a runtime of a component, and its dependencies declared externally:
              - Unmatched attributes:
                  - Provides documentation but the consumer didn't ask for it
                  - Provides javadocs but the consumer didn't ask for it
                  - Doesn't say anything about its target Java version (required compatibility with Java 13)
                  - Doesn't say anything about its elements (required them packaged as a jar)
                  - Provides release status but the consumer didn't ask for it
          - Variant 'runtimeElementsWithFixedAttribute' capability org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.10 declares a runtime of a component compatible with Java 8, packaged as a jar, and its dependencies declared externally:
              - Unmatched attributes:
                  - Provides a library but the consumer didn't ask for it
                  - Provides attribute 'org.gradle.jvm.environment' with value 'standard-jvm' but the consumer didn't ask for it
                  - Provides release status but the consumer didn't ask for it
          - Variant 'sourcesElements' capability org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.10 declares a runtime of a component, and its dependencies declared externally:
              - Unmatched attributes:
                  - Provides documentation but the consumer didn't ask for it
                  - Provides sources but the consumer didn't ask for it
                  - Doesn't say anything about its target Java version (required compatibility with Java 13)
                  - Doesn't say anything about its elements (required them packaged as a jar)
                  - Provides release status but the consumer didn't ask for it
        The following variants were also considered but didn't match the requested attributes:
          - Variant 'apiElementsWithFixedAttribute' capability org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.10 declares a component compatible with Java 8, packaged as a jar, and its dependencies declared externally:
              - Incompatible because this component declares an API of a component and the consumer needed a runtime of a component
          - Variant 'gradle70ApiElements' capability org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.10 declares a component compatible with Java 8, packaged as a jar, and its dependencies declared externally:
              - Incompatible because this component declares an API of a component and the consumer needed a runtime of a component
> Failed to notify project evaluation listener.
   > Could not get unknown property 'android' for project ':flutter_web_auth_2' of type org.gradle.api.Project.
   > Could not get unknown property 'android' for project ':flutter_web_auth_2' of type org.gradle.api.Project.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 2s
Running Gradle task 'assembleRelease'...                            3.3s
Gradle task assembleRelease failed with exit code 1

Help! I want to use flutter_web_auth_2 for web app

Hello,

I want to use flutter_web_auth_2 for web app.

I test my application with visual studio code.

I have this error : flutter: Invalid argument(s): Callback url scheme must start with http://localhost:{port}

This is my code :

import 'package:flutter/material.dart';
import 'package:flutter_web_auth_2/flutter_web_auth_2.dart';

class HomeController {
  final String pageTitle = 'Jukebox';
  final String clientId =
      'YOUR_CLIENT_ID'; // Remplacez par votre client ID Spotify
  final String redirectUri =
      'http://localhost:8080'; // Remplacez par votre URL de redirection Spotify

  Future<void> handleConnectToSpotify(BuildContext context) async {
    const authorizationEndpoint = 'https://accounts.spotify.com/authorize';
    const responseType = 'token';
    const scope =
        'user-read-private user-read-email'; // Définissez les scopes que vous souhaitez utiliser
    final authUrl =
        '$authorizationEndpoint?response_type=$responseType&client_id=$clientId&redirect_uri=$redirectUri&scope=$scope';

    try {
      final result = await FlutterWebAuth2.authenticate(
        url: authUrl,
        callbackUrlScheme: 'jukebox',
      );

      // Le jeton d'accès est inclus dans l'URL de redirection
      final token = Uri.parse(result).fragment.split('&').first.split('=').last;

      // Utilisez le jeton d'accès pour accéder aux ressources protégées
      // ...
    } catch (e) {
      // Gérez les erreurs d'authentification ici
      print(e);
    }
  }
}

Can you help me ?

Thanks in advance

Keyboard not showing when activating text field in web view

Describe the bug

We use this plugin in conjunction with Azure AD to sign into company accounts.

Bringing up the the "in-app browser" (ASWebAuthenticationSession) on iOS works fine, but sometimes tapping into the username/email field in the Microsoft login page does not bring up the keyboard. (The field is also auto-focused on the initial page, but alas the keyboard is not showing.)

I see no errors in the console, and the login screen of our Flutter app is also not doing anything "special" with the Keyboard (no Flutter-field even had focus until this point), so I don't have a guess as to what could be the issue here right now.

To Reproduce

Steps to reproduce the behavior:

  1. Launch our sign in URL with flutter_web_auth_2
  2. Get redirected to the Microsoft-hosted login page

Expected behavior

The in-app browser should work normally. Focusing a text field should bring up the keyboard.

Screenshots

CleanShot 2022-10-24 at 12 35 49@2x

As you can see the field is active (showing the menu), but the keyboard has not shown.

Device

  • Device: iPad mini (6th gen)
  • OS: iPad OS 15.7
  • Browser: "Safari" through flutter_web_auth_2
  • flutter_web_auth_2 version: 1.1.2

Unhandled Exception: MissingPluginException in iOS simulator

Describe the bug

An error in the iOS simulator occurs when it tries to execute this line…

final response = await FlutterWebAuth2.authenticate(url: url_authorize_compose, callbackUrlScheme: callback_url_scheme);

To Reproduce

Steps to reproduce the behavior:

  1. Go to authenticate view
  2. Click on authenticate CTA
  3. See error on the console... the app crashes

Expected behavior

it should open the 3rd party authenticate page

Screenshots

image

Device (please complete the following information!)

  • Device: Launching lib/main.dart on iPhone 14 Pro Max in debug mode...
  • OS: iOS 16.2 in Simulator
  • flutter_web_auth_2 version: 2.0.3

image

Additional context

Same code in Android simulator, works perfectly

Authenticate in multiple activities

Describe the bug

Our app has two activities implemented: ActivityA and ActivityB.
When executing the authenticate function in ActivityB, it redirects to ActivityA.

To Reproduce

Steps to reproduce the behavior:

  1. Launch the ActivityB.
  2. Execute the authenticate function.
  3. Observe the redirect to ActivityA.

Expected behavior

Redirect to the Activity that performed the authenticate.

Screenshots

Not applicable.

Device

  • Device: Pixcel7Pro
  • OS: Android13
  • Browser: Chrome
  • flutter_web_auth_2 version: 2.1.2

Additional context

ActivityA has the following intent-filter:

<intent-filter>
  <action android:name="android.intent.action.MAIN"/>
  <category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>

This filter is used to launch the main screen of the app.

ActivityB is set up to receive text data with the following intent-filter:

<intent-filter>
  <action android:name="android.intent.action.SEND"/>
  <category android:name="android.intent.category.DEFAULT"/>
  <data android:mimeType="text/plain"/>
</intent-filter>

CallbackActivity is defined as follows.

<activity
    android:name="com.linusu.flutter_web_auth_2.CallbackActivity"
    android:exported="true">
        <intent-filter android:label="flutter_web_auth_2">
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="com.example.oauth" android:host="callback" />
          </intent-filter>
</activity>

Checklist

  • I have read and followed the entire troubleshooting guide and it has not provided the solution I need.
  • I have provided all the information I can (incl. auth URL etc.)

[Web] Detect login tab was closed or cancelled

Describe the bug

On web we’re using this package for discord login. ‘authenticate’ method opens a new tab with the proper url. But when I close the new tab, in the flutter app ‘authenticate’ method stays running. Could you please help us how can we resolve it?

Windows Callback URI Scheme other than http://localhost

Hi like i mentioned here appwrite/sdk-for-flutter#96 (comment) I found a potential solution for the callback-uri-scheme.
With this package https://pub.dev/packages/desktop_webview_window we could open a WebView window and call the Auth Url after the login process a URL change to our callback-uri-scheme will happen this can be catched with a registration here void addOnUrlRequestCallback(OnUrlRequestCallback callback);.

For the transition time i would say that we implement it as an additional feature.

So if a callback-uri-scheme is provided which is not fitting this Constraints

if (callbackUri.scheme != 'http' ||
(callbackUri.host != 'localhost' && callbackUri.host != '127.0.0.1') ||
!callbackUri.hasPort) {
throw ArgumentError(
'Callback url scheme must start with http://localhost:{port}',
);
}

Use the in App WebView

If wanted I will provide an PR for this.

Mac OS error: found nil while unwrapping an Optional value => lost Connection to Device => App Closes

Describe the bug

I was trying to use the flutter_web_auth_2 Plugin for my Flutter App, on IOS and Web it works Great, but on my Mac, wenn the _platform.authenticate Method is Called the App Closes Instantly and in the Debug Output are the following Messages:
flutter_web_auth_2/FlutterWebAuth2Plugin.swift:39: Fatal error: Unexpectedly found nil while unwrapping an Optional value
Lost connection to device.
Exited

To Reproduce

Steps to reproduce the behavior:
the Parameters are:

url: https://domain.auth0.com/authorize?response_type=code&client_id=clientID&redirect_uri=workingRedirectURI&state=state&code_challenge=codeChallenge&code_challenge_method=S256

callbackUrlScheme: workingRedirectScheme

preferEphemeral: false

redirectOriginOverride: null

I found nothing Helpful in the Issues or the Troubleshoot guide so I Think its a Bug?

URL Interceptor / Listener feature

Is your feature request related to a problem? Please describe.

Firstly, thanks for the amazing package. It works well with multiple OAuth providers.

Though I'm wondering if it's possible to implement an onUrlChanged callback to listen to changes in URL? Reason being, sometimes the URL may contain error information that can be logged to help debug production errors. Currently if there's an error, it is displayed only in the WebView.

Or sometimes user navigates to a wrong page and we'd like to close the webview and notify them.

Describe the solution you'd like

A callback with the signature void Function (String) that is called whenever currently active URL is changed.

Windows support

Hi,

does this plugin support Windows?
Its tagged with windows but there is nothing about windows in the readme/description at pub.dev

It would be nice if it does because its pain to handle it :)

Redirect URI results in DNS

Issue

I am trying to authenticate a user with LinkedIn.
I am able to get all the way to the authorize screen but when the user has successfully signed in the redirect URI tries to target a website instead of redirecting back into the app.
The redirect URI is not a website so it just loads a DNS error on the web page.

How do I redirect back int the app?

Android Manifest

`<activity android:name="com.linusu.flutter_web_auth_2.CallbackActivity" android:exported="true">
            <intent-filter android:label="flutter_web_auth_2">
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="social-login" android:host="callback" />
            </intent-filter>
</activity>

Dart code

var encoded = Uri.encodeComponent('https://social-login/callback');
final url = Uri.parse("https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=*********&redirect_uri=$encoded&scope=w_member_social");
        try {
          final result =
              await FlutterWebAuth2.authenticate(url: url.toString(), callbackUrlScheme: 'social-login');
          print('successs');
          print(result);
        } on PlatformException catch (e) {
          print('error');
          print(e.message);
          print(e.details);
        }

Call back URL as per Linkedin

image

Device used

Samsung s10

Additionally

I am also trying to log into TikTok and I am facing the same issue where it tries redirecting to the URI instead of the back to the app

Any help would be greatly appreciated 😎

Redirect url fails with Windows AD authentication - msauth links are blocked

Describe the bug

When I login with windows AD authentication, redirect url gets blocked on successful authentication. The redirect url would be somthing as msasuth://com.xxx.xxxxx

This works fine for azure cloud but not for windows AD with same web_auth2 library.

To Reproduce

Steps to reproduce the behavior:

  1. Callback url scheme is set as msauth

  2. Androidmanifest.xml file has below details -
    image

  3. On trying authenticating with a windows AD server, a pop up is shown to enter user name and password. After entering the user name and password, the in app browser shows msauth links blocked.

  4. Same configuration works for Azure AD but not for windows AD using authorization code flow.

  5. The tricky part is, when we immediately try to authenticate the system, it works fine.

Expected behavior

After successful authentication, should be redirected back to

Screenshots

If applicable, add screenshots to help explain your problem.

Device (please complete the following information!)

  • Device: [Android emulator]

image

  • OS: [e.g. iOS 8.1, Windows 10 21H2]
  • Browser: [Chrome]
  • flutter_web_auth_2 version: [2.0.0]

Additional context

Add any other context about the problem here.

WebView Browser stays open after successful call to FlutterWebAuth2.authenticate Android

Describe the bug

This is the same report as this bug on flutter_web_auth: LinusU#133
It also exists on this package, so I thought I would report it here

On android, if you successfully authenticate with FlutterWebAuth2.authenticate, when you are redirected back to the app, the browser tab used to authenticate you is still open in the app switcher. This tab is no longer needed so I think it should be closed?

To Reproduce

Steps to reproduce the behaviour:

  1. Successfully authenticate on an android device
  2. Go to app switcher
  3. See that browser tab is still open

Expected behaviour

I think that after a successful .authenticate, the browser tab should be closed as it is no longer needed

Screenshots

Device (please complete the following information!)

  • Device: Android pixel 6 simulator, tiramisu. (Happens on any android device)
  • OS: tiramisu, API level 33
  • flutter_web_auth_2 version: 2.0.0

Additional context

I know that preferEphemeral: true makes the tab close, but it also closes the tab if the user goes to a different app during the login (e.g. to copy a password/mfa code) I think that either Ephemeral tabs should stay open during the login process, or normal tabs should close upon a successful .authenticate

Checklist

  • [yup] I have read and followed the entire troubleshooting guide and it has not provided the solution I need.
  • [yup] I have provided all the information I can (incl. auth URL etc.) - auth URL is irrelevant to this issue.

Any help is appreciated thanks.

HTTPS Scheme

I'm using flutter_webview and want integrate OAuth.
Any methods to use https scheme?

Just dont return back to my flutter app after authentication.

Like this:

<data android:scheme="https" android:host="mydomain.com" android:pathPrefix="/callback" />

await FlutterWebAuth2.authenticate( url: request.url, callbackUrlScheme: 'https', );

Change win32 dependency version

Description

Hi, could you change win32 dependency version to ^2.0.0?

You lib is causing error on pub get command:

Because flutter_web_auth_2 >=1.1.0 depends on flutter_web_auth_2_windows ^1.1.0 which depends on win32 ^3.0.0, flutter_web_auth_2 >=1.1.0 requires win32 ^3.0.0. Because path_provider_windows >=2.1.1 depends on win32 ^2.1.0 and path_provider_windows >=2.0.0 <2.1.1 depends on win32 ^2.0.0, path_provider_windows >=2.0.0 requires win32 ^2.0.0. Thus, flutter_web_auth_2 >=1.1.0 is incompatible with path_provider_windows >=2.0.0. And because shared_preferences_windows >=2.0.0 depends on path_provider_windows ^2.0.0, flutter_web_auth_2 >=1.1.0 is incompatible with shared_preferences_windows >=2.0.0. And because shared_preferences 2.0.15 depends on shared_preferences_windows ^2.0.1 and no versions of shared_preferences match >2.0.15 <3.0.0, flutter_web_auth_2 >=1.1.0 is incompatible with shared_preferences ^2.0.15. So, because qapp2 depends on both shared_preferences ^2.0.15 and flutter_web_auth_2 ^1.1.0, version solving failed. pub get failed (1; So, because qapp2 depends on both shared_preferences ^2.0.15 and flutter_web_auth_2 ^1.1.0, version solving failed.)

To Reproduce

Just add shared_preferences: ^2.0.15 dependency or package_info_plus: ^1.4.3+1

window.opener is null in auth.html

Describe the bug

when trying to authenticate against twitter using twitter_oauth2_pkce which just uses flutter_web_auth_2 in the backend I managed to let it open the popup with correct redirect but when auth.html is called the window.opener.postMessage does not work since window.opener is null.

Expected behavior

window.opener should not be null or any other way to send the data back to it's parrent

Device (please complete the following information!)

  • OS: arch linux
  • Browser: Chromium
  • flutter_web_auth_2: ^2.0.4 (used by twitter-oauth2_pkce)

Unable to build on MacOS after raising minimum target version to 10.15 (11.0)

Describe the bug

Attempting to build for MacOS fails with cocopods install step failing. I've tried raising the minimum target version in the MacOs Podfile as well as in XCode Project but I still see the error.

dlopen(/opt/homebrew/lib/ruby/gems/3.2.0/gems/ffi-1.15.5/lib/ffi_c.bundle, 0x0009): Library not loaded

Also I've tried all the main suggestions of reinstalling gem and cocoapods and updating Ruby and in all cases I still see the same problem.

I thought this was a flutter issue to begin with and posted here but I was informed that it was likely due to my target version in the MacOS app.

I have not tried to build this for iOS but suspect that I will run into the same issue and probably has the same fix of updating the target version appropriately.

I'm not sure if I'm currently updating the minimum target version correctly or if there are some other places that I'm missing out on in order to get this to work.

To Reproduce

Steps to reproduce the behavior:

  1. Create a new flutter project flutter create bug --platforms macos
  2. Add the Flutter Web Auth 2 as a dep: flutter pub add flutter_web_auth_2
  3. Raise minimum target version in Podfile and in XCode Project
    • I modify the first line of the Podfile in the macos folder setting the version to 10.15 (i've tried 11.0 too).
      • platform :osx, '11.0'
    • I open the XCode Project -> Runner -> Target -> Runner -> Minimum Target Version -> 10.15 (or 11.0)
  4. In the macos folder invoke pod install cd macos; pod install
dlopen(/opt/homebrew/lib/ruby/gems/3.2.0/gems/ffi-1.15.5/lib/ffi_c.bundle, 0x0009): Library not loaded

Expected behavior

I should be able to build on Mac OS.

Screenshots

Updated Mac OS Minimum Target version in the Xcode prooject
Screenshot 2023-07-30 at 1 32 31 PM

Device (please complete the following information!)

  • Device: Macbook Air M1
  • OS: 13.4.1
  • Browser: Chrome
  • flutter_web_auth_2 version: 2.1.5

Checklist

  • I have read and followed the entire troubleshooting guide and it has not provided the solution I need.
  • I have provided all the information I can (incl. auth URL etc.)

Can't get web auth to work with my own authentication server

Describe the bug

I can't get the authentication to work for the web platform. The authentication works on Android

To Reproduce

I have my own authentication/backend service to authenticate my users. The service is written in Go. The authentication flow works like this:

  • the client queries http://localhost:8080/auth/facebook
  • the client is redirected to a facebook page where the user will authorize my app
  • facebook then redirects to http://localhost:8080/auth/callback with the user info (I do stuff with this data, like adding the user to a database)

The above works when the client is a simple html page that I serve from the /login.html endpoint of the backend. This html pages just contains a link that points to http://localhost:8080/auth/facebook.

I'm now trying to build a proper UI with Flutter. So far I have something like this:

import 'package:flutter/material.dart';
import 'package:social_login_buttons/social_login_buttons.dart';
import 'package:flutter_web_auth_2/flutter_web_auth_2.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Test',
      home: LoginPage(),
    );
  }
}

class LoginPage extends StatelessWidget {
  LoginPage({super.key});

  @override
  Widget build(BuildContext context) {

    return LayoutBuilder(builder: (context, constraints) {
      return Scaffold(
        body: SocialLoginButton(
          buttonType: SocialLoginButtonType.facebook,
          onPressed: () async {
            final result = await FlutterWebAuth2.authenticate(
                url: "http://localhost:8080/auth/facebook", callbackUrlScheme: "callback-scheme");

            print("result: $result");

          },
        ),
      );
    });
  }
}

On the server side, there are just 2 simple functions that are called. The Login function (behing the /auth/facebook endpoint), which creates a Oauth link that the client will need to follow to start the auth flow:

func Login(c *gin.Context) {
        ...
	url, err := gothic.GetAuthURL(c.Writer, c.Request)

	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
	}

	c.Redirect(http.StatusFound, url)
}

And the AuthCallback function, behind the /auth/callback endpoint. This endpoint serves the auth.html page from your doc

func AuthCallback(c *gin.Context) {
	user, err := gothic.CompleteUserAuth(c.Writer, c.Request)

        ...

	c.HTML(http.StatusOK, "auth.html", gin.H{})
	// c.Redirect(http.StatusFound, "callback-scheme://")  // This makes it work with Android
}

This setup works for Android when the backend redirects to callback-scheme://. However it doesn't work for the web platform: when I click the login button, another tab opens with Facebook, I can give permissions for my app, then I'm redirected to the auth.html page. The page is closed almost immediately (makes sense, since we're doing window.close() there). But this line in the flutter app is never executed:

            print("result: $result");

And obviously if it's not executed, I can't get the token back.

Expected behavior

The auth.html page should be able to send information back to the main app.

Device (please complete the following information!)

  • Device: Desktop computer
  • OS: Archlinux
  • Browser: Chrome
  • flutter_web_auth_2 version: latest as of 21/04/2023 (DD/MM/YY)

Additional context

Add any other context about the problem here.

Checklist

  • [ x ] I have read and followed the entire troubleshooting guide and it has not provided the solution I need.
  • [ x ] I have provided all the information I can (incl. auth URL etc.)

Issues expected when receiving access token as query parameters

If an access_token is transferred as a query parameter from a separate server (for example, a spring boot), this method appears to be at risk of being stolen before receiving the token from the flutter. By any chance, Uri.parse(result).Is there a way to get the data delivered to .body instead of .queryParameters??

iOS Opening File Insted of URL [Authenticate Call]

After calling this authenticate method on my auth URL on IOS it is opening like this. Whereas on all other platforms it is opening correctly.

To Reproduce

Steps to reproduce the behavior:

  1. Go to 'await FlutterWebAuth2.authenticate()'
  2. I am using Salesforce login redirect.
  3. Works on all other platforms but Showing below thing on iOS.

Simulator Screenshot - iPhone 14 Pro Max - 2023-07-25 at 09 39 59

[flutter_web_auth_2] iOS15.5 [AuthenticationSession] The provided scheme is not valid. A scheme should not include special characters such as ":" or "/".

Describe the bug

[flutter_web_auth_2] on iOS15.5 Exception: [AuthenticationSession] The provided scheme is not valid. A scheme should not include special characters such as ":" or "/".

To Reproduce

example code with calbackurlscheme[com.xxxx://logincalback]

Device (please complete the following information!)

  • Device: Simulator iPhon13 Pro
  • OS: iOS15.5
  • Browser: Safari
  • flutter_web_auth_2 version: 1.1.2

Additional context

on iOS14 ,without the error, but auth0 authorize page is always loading !

IOS: Missing Plugin Implementation

Describe the bug

When I authenticate to my custom backend in the iOS app, I get this error!
Error: MissingPluginException(No implementation found for method authenticate on channel flutter_web_auth_2)

To Reproduce

Steps to reproduce the behavior:

  1. You can run the example given in the package itself

Expected behavior

It should work

Device

Device: iPad Pro 9.7"
OS: iOS 15.0.2
flutter_web_auth_2 version: 1.1.2

Additional context

Maybe I am missing some documentation here but I followed everything in the readme

[MacOS] PlatformExeption: Failed to aquire root FlutterViewController

Describe the bug

Getting a PlatformExeption from running FlutterWebAuth2.authenticate on a mac.

Device (please complete the following information!)

  • Device: Macbook Pro
  • OS: MacOS V12.6
  • flutter_web_auth_2 version: 1.1.2

Code

try {
      final result = await FlutterWebAuth2.authenticate(
        url:
            "https://example.com",
        callbackUrlScheme: "example",
      );
} catch (error) {
      print(error);
}

WEB: invalid callbackUrlScheme error

Describe the bug

After updating the library from version 2.0.0 to the latest version I'm not able to authenticate when running app on WEB. I always receive the error: Error: Invalid argument (callbackUrlScheme): must be a valid URL scheme:

To Reproduce

Pass any web url as callbackUrlScheme e.g. http://localhost:8080/auth.html or https://yourdomain/auth.html

Device (please complete the following information!)

  • Browser: [Chrome]
  • flutter_web_auth_2 version: >= 2.0.1

Additional context

After some investigation I think that the issue is due to the _assertCallbackScheme method:

static void _assertCallbackScheme(String callbackUrlScheme) {
    **if (!_schemeRegExp.hasMatch(callbackUrlScheme) &&
        (kIsWeb || (!Platform.isWindows && !Platform.isLinux)))** {
      throw ArgumentError.value(
        callbackUrlScheme,
        'callbackUrlScheme',
        'must be a valid URL scheme',
      );
    }
  }

I think that the check should behave for web like for windows/linux:

**if (!_schemeRegExp.hasMatch(callbackUrlScheme) &&
        (!kIsWeb && !Platform.isWindows && !Platform.isLinux))** {
      throw ArgumentError.value(
        callbackUrlScheme,
        'callbackUrlScheme',
        'must be a valid URL scheme',
      );
    }

I can contribute and open a PR with the fix.
Let me know what do you think

doesn't capture my callback

same as title doesn't capture my callback.don't why

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_web_auth/flutter_web_auth.dart';
import 'package:flutter_web_auth_2/flutter_web_auth_2.dart';

import 'dart:convert' show jsonDecode;
import 'package:http/http.dart' as http;

// App specific variables
final googleClientId = 'client';
final callbackUrlScheme = 'com.example.ui://callback';

// Construct the url
final url = Uri.https('bungie.com', '/en/oauth/authorize', {
'client_id': googleClientId,
'response_type': 'code',
});

// Present the dialog to the user
Future<String?> getGoogleAuthCode() async {
final result = await FlutterWebAuth2.authenticate(
url: url.toString(),
callbackUrlScheme: callbackUrlScheme,
);

// Extract the code from the response URL

//String casteo = getGoogleAuthCode().toString();
//final result = await FlutterWebAuth2.authenticate(url: url.toString(), callbackUrlScheme: callbackUrlScheme);

// Extract code from resulting url
final result1 = Uri.parse(result).queryParameters['code'];
print(result) {
// TODO: implement print
throw UnimplementedError();
}

var headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'code': '$result1',
};
var request = http.Request(
'POST', Uri.parse('https://www.bungie.net/platform/app/oauth/token'));

request.headers.addAll(headers);

http.StreamedResponse response = await request.send();

if (response.statusCode == 200) {
print(await response.stream.bytesToString());
} else {
print(response.reasonPhrase);
}

// Extract the access token from the response
//final data = jsonDecode(response.body);

// Use the access token to access the Google API

// Do something with the data
}

void main() {
runApp(miercoles());
}

class miercoles extends StatelessWidget {
@OverRide
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Google Sign In'),
),
body: Center(
child: ElevatedButton(
child: Text('Sign in with Google'),
onPressed: () async {
// Get the auth code

          getGoogleAuthCode();
        },
      ),
    ),
  ),
);

}
}
my android manifest
<activity android:name="com.linusu.flutter_web_auth.CallbackActivity" android:exported="true" tools:ignore="MissingClass"> <intent-filter android:label="flutter_web_auth_2"> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="com.example.ui://callback" /> </intent-filter> </activity>

Change iOS dialog text

When using the plugin on iOS for first time it asks
"test.com" would like to sign in.
Is these any way to change this text since I am using the package for payment and not for Sign In

Redirect not working when deployed, only using localhost

Hello, it seems i cant get this working and not sure if it is a bug or not. I have working code that allows me to log fine when using localhost. But as soon as I deploy it on IIS and change the redirect url to the hosting ip, it stops working. I am using the flutter web version so i use a static .html page to redirect to. This page works fine as I can call it manually when the site is hosted. But when i try to run the FlutterWebAuth2.authenticate method, and sign in, it never returns to code. So im guessing the redirect isnt working for some reason. Really not sure why as again I can redirect to the static html page manually from my PC to the hosting PC.

Here is a bit of my code, but there isnt much to see really.

String url1String = 'https://test-api1.xxx.com/v1/user/authorization?response_type=code&client_id=XXXredirect_uri=http://xx.xx.xx.xx:80/logindirect.html&scope=uid%20openid%20email%20profile_conexiom';

final result = await FlutterWebAuth2.authenticate(url: url1String, callbackUrlScheme: 'http');

  final code = Uri.parse(result).queryParameters['code'];

When this is used like this: with localhost:49430, it works fine. What gives?

String url1String = 'https://test-api1.xxx.com/v1/user/authorization?response_type=code&client_id=XXXredirect_uri=http://localhost:49430/logindirect.html&scope=uid%20openid%20email%20profile_conexiom';

Working with fixed redirects not in my app domain

I apologize for creating an issue when what I'm really doing is trying to get some help.

I'm trying to connect to the Tesla Auth provider (which is unofficially documented here) and trying to use Flutter Web Auth 2 to perform the front channel flow and allow my user to authorize my app and obtain the access and refresh tokens. Unfortunately at this time, Tesla doesn't really cater to other third-party apps and basically most third-party apps out there masquerade as the Tesla App. The OAuth front channel workflow uses a fixed redirect callback URL of https://auth.tesla.com/void/callback which is not a real page on Tesla and the authorization code is delivered as a query parameter to that URL.
My question is, would I be able to intercept this redirect using Flutter Web Auth 2 (or in general) and obtain the URL? As of now I'm not sure how to go about doing this. I'm hoping to use this on desktop, mobile and web and was wondering if there are some platforms where this will work at least.

Again I apologize for creating an issue given that this is not a real bug. I'm new to web programming and OAuth so please forgive my ignorance.

Closing the authentication tab keeps authenticate method running

Describe the bug

If the authentication tab in the browser is closed before receiving the authentication result, the FlutterWebAuth2.authenticate keeps running.

To Reproduce

Steps to reproduce the behavior:

  1. Start authentication with a provider that has a dialog asking the user to approve scopes (e.g. Github with scopes repo, project)
  2. Close the github browser tab
  3. FlutterWebAuth2.authenticate runs indefinitely

Expected behavior

FlutterWebAuth2.authenticate returns null or throws an Exception

Screenshots

Line 26 is never reached if browser tab is closed
image

Device (please complete the following information!)

  • Device: Desktop Computer
  • OS: Windows 11 22H2
  • Browser: Chrome,
  • flutter_web_auth_2 version: 2.1.2

Additional context

Checklist

  • I have read and followed the entire troubleshooting guide and it has not provided the solution I need.
  • I have provided all the information I can (incl. auth URL etc.)

Fatal error: Unexpectedly found nil while unwrapping an Optional value

Describe the bug

App crashes after second time I initialize oauth2 flow in IOS.

To Reproduce

Steps to reproduce the behavior:

  1. Click on a dynamic link to initialize the app with oauth flow
  2. Authentication completes succesfully
  3. Everthing works unless you click the dynamic link once more
  4. You see the error: flutter_web_auth_2/SwiftFlutterWebAuth2Plugin.swift:29: Fatal error: Unexpectedly found nil while unwrapping an Optional value

Device (please complete the following information!)

  • Device: Iphone 13
  • OS: iOS 16.1.1
  • flutter_web_auth_2 version: 2.2.1

Support In-App WebView

Describe the bug

Firebase BackEnd does n't support external callable method

To Reproduce

Steps to reproduce the behavior:

  1. Create FireBase project
  2. provide any Auth Provider as Google
  3. try to Authentication with external browser tab
  4. See Error :
    Unable to process request due to missing initial state. This may happen if browser sessionStorage is inaccessible or accidentally cleared.

Expected behavior

After Authentication , callable method fire and get back to App .

Screenshots

103522266-1f317180-4ea0-11eb-808f-50539f604b01

Device (please complete the following information!)

  • Device: [ OPPO F11 ]
  • OS: [Andriod 12]
  • Browser: [Chrome]
  • flutter_web_auth version: [e.g. 0.4.1]

Additional context

if add support to in_App_Webview that will be great

Help! I try to use flutter_web_auth_2 on web app

Describe the bug

A clear and concise description of what the bug is.
Hello,

I want to use flutter_web_auth_2 for web app.

I test my application with visual studio code.

I have this error : flutter: Invalid argument(s): Callback url scheme must start with http://localhost:{port}

Can you help me ?

Thanks in advance

To Reproduce

This is my code :

import 'package:flutter/material.dart';
import 'package:flutter_web_auth_2/flutter_web_auth_2.dart';

class HomeController {
  final String pageTitle = 'Jukebox';
  final String clientId =
      'YOUR_CLIENT_ID'; // Remplacez par votre client ID Spotify
  final String redirectUri =
      'http://localhost:8080'; // Remplacez par votre URL de redirection Spotify

  Future<void> handleConnectToSpotify(BuildContext context) async {
    const authorizationEndpoint = 'https://accounts.spotify.com/authorize';
    const responseType = 'token';
    const scope =
        'user-read-private user-read-email'; // Définissez les scopes que vous souhaitez utiliser
    final authUrl =
        '$authorizationEndpoint?response_type=$responseType&client_id=$clientId&redirect_uri=$redirectUri&scope=$scope';

    try {
      final result = await FlutterWebAuth2.authenticate(
        url: authUrl,
        callbackUrlScheme: 'jukebox',
      );

      // Le jeton d'accès est inclus dans l'URL de redirection
      final token = Uri.parse(result).fragment.split('&').first.split('=').last;

      // Utilisez le jeton d'accès pour accéder aux ressources protégées
      // ...
    } catch (e) {
      // Gérez les erreurs d'authentification ici
      print(e);
    }
  }
}

Checklist

  • [X ] I have read and followed the entire troubleshooting guide and it has not provided the solution I need.
  • [X ] I have provided all the information I can (incl. auth URL etc.)

I try to set redirectUri = 'http://localhost:{port}'

Failed to build (APK/Appbundle) on Android

Iam using package appwrite pub dev which depends on this package. when i build IOS working fine, but when i build APK/Appbundle Android it showing error that says:

  • What went wrong:
    A problem occurred evaluating project ':flutter_web_auth_2'.

No signature of method: build_br839y3cjw240hfyqvnkgs25f.android() is applicable for argument types: (build_br839y3cjw240hfyqvnkgs25f$_run_closure2) values: [build_br839y3cjw240hfyqvnkgs25f$_run_closure2@54024517]

my flutter version: 3.3.8

Flutter Web Auth 2.1.3 does not use the correct Flutter Web Auth 2 Platform Interfaces

Describe the bug

A clear and concise description of what the bug is.

To Reproduce

Steps to reproduce the behavior:

  1. Update the version to ^2.1.3
  2. try to run tests
  3. try to run the code

Expected behavior

The minor version update should work without any problems

Actual behavior

it does not work for chrome or tests are not running

: Error: The method 'FlutterWebAuth2WindowsPlugin.authenticate' doesn't have the named parameter 'contextArgs' of overridden method 'FlutterWebAuth2Platform.authenticate'.
flutter_web_auth_2_windows.dart:55
  Future<String> authenticate({
                 ^
: Context: This is the overridden method ('authenticate').
flutter_web_auth_2_platform_interface.dart:26

Device (please complete the following information!)

  • Browser: Chrome
  • flutter_web_auth_2 version: update ^2.1.2 to 2.1.3

Additional context

the newest version still points on the flutter web auth 2 platform version 2.1.0 instead of 2.1.3. As this is a breaking change we should use semantic versioning instead of increasing a minor version. so it should be 2.2.0

Checklist

  • I have read and followed the entire troubleshooting guide and it has not provided the solution I need.
  • I have provided all the information I can (incl. auth URL etc.)

Issue prompting for authentication on OSX with Chrome as default browser

Describe the bug

This is a re-post of LinusU#136 .

When using flutter_web_auth v0.4.1 (or flutter_web_auth_2 on v1.1.2) on Darwin OSX (12.5.1) targets that have the default browser set to Chrome (Version 105.0.5195.102 (Official Build) (x86_64)), the authentication prompt opens and closes immediately afterwards, causing a PlatformException. If the default browser is set to Safari, the authentication flows work as expected.

To Reproduce

Steps to reproduce the behavior:

  1. Set Chrome as default browser in OSX
  2. Start the authentication flow with the default browser (Chrome), using flutter_web_auth v0.4.1
  3. See the chrome window open and immediately close
  4. Stack trace:
[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: PlatformException(EUNKNOWN, The operation couldn’t be completed. (com.apple.AuthenticationServices.WebAuthenticationSession error 3.), null, null)
#0      StandardMethodCodec.decodeEnvelope
package:flutter//services/message_codecs.dart:653
#1      MethodChannel._invokeMethod
package:flutter//services/platform_channel.dart:296
<asynchronous suspension>
#2      FlutterWebAuth2MethodChannel.authenticate
package:flutter_web_auth_2_platform_interface/flutter_web_auth_2_method_channel.dart:14
<asynchronous suspension>
#3      auth2

Expected behavior

The Chrome window should have opened on the correct URL, instead of not opening at all (when Chrome is already open) or opening on the "Chrome Profile Selection Page".

Screenshots

N/A

Device (please complete the following information!)

  • Device: MacBook Pro
  • OS: Darwin 12.5.1 and 12.6
  • Browser: Chrome
  • flutter_web_auth_2 version: 1.1.2

Additional context

N/A

On Android, call to authenticate immediately returns CANCELED

Describe the bug

When I make the call to FlutterWebAuth2.authenticate, the web view does not open, and it immediately returns PlatformException(CANCELED, User canceled login, null, null).

To Reproduce

Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior

When FlutterWebAuth2.authenticate is called, a web view should open to the given url.

Screenshots

If applicable, add screenshots to help explain your problem.

Device (please complete the following information!)

  • Device: OnePlus LE2115
  • OS: Android 12
  • Browser: Chrome
  • flutter_web_auth_2 version: 1.1.2

Additional context

I can only reproduce this issue once our android app is built in release mode and distributed through the Play store. I cannot reproduce it when building locally with Android Studio in either debug or release mode. It also can not reproduce this issue in our iOS app (same flutter code).

Feature Request: Generalize URL launch and redirect listening

First and foremost, I'd like to thank you for your work on this package. The feature of launching a URL and listening for the redirect URL across iOS, Android, and Web platforms is a standout feature and works brilliantly.

I'm reaching out to propose a possible extension of this functionality. While this feature is primarily used for authenticating users, it also has potential utility in other scenarios. One such instance is user sign-out.

In my application, I need to sign users out by redirecting them to a specific logout URL, and then ensure that the sign-out was successful by listening for a redirect URL from the server. As the flutter_web_auth_2 package already has the underlying mechanics to perform this, it would be incredibly useful if this functionality could be generalized to handle such cases.

I look forward to hearing your thoughts on this proposal. Thank you for your time and consideration.

Windows callbackUrlScheme are invalid

Describe the bug

When you run your example app, or any other implementation, it is not possible to give a valid callbackUrlScheme for windows, as windows needs a scheme that matchs RegEx() and you check the scheme before with RegEx, it is not possible to start a windows authentication.

To Reproduce

Steps to reproduce the behavior:

  1. Go to 'example/lib/main.dart'
  2. Run the app
  3. Click on 'Authenticate'
  4. See error

Expected behavior

It is possible to add a callbackUrlScheme for windows that matchs the RegEx from the plattform implementation.

Device (please complete the following information!)

  • Device: Windows PC
  • OS: Windows
  • flutter_web_auth_2 version: 2.0.1

Additional context

/flutter_web_auth_2/lib/flutter_web_auth_2.dart in line 62 and flutter_web_auth_2/lib/src/flutter_web_auth_2_windows.dart line 66 close each other.

Fix

#23 for the fix

Windows: Missing Plugin Implementation

Describe the bug

When I authenticate to my custom backend in the windows app, I get this error!
Error: MissingPluginException(No implementation found for method authenticate on channel flutter_web_auth_2)

I believed in pub.dev/flutter_web_auth_2 , it shows the support for windows as well

To Reproduce

Steps to reproduce the behavior:

  1. You can run the example given in the package itself

Expected behavior

It should work

Device (please complete the following information!)

  • Device: Desktop Computer
  • OS: [e.g. iOS 8.1, Windows 11 22H2]
  • flutter_web_auth_2 version: 1.0.1 (can't use 1.1.0 due to dependency constraints with device_info_plugin)

Additional context

Maybe I am missing some documentation here or somethings not working internally.

Unable to Capture Redirect URLs with 'http' or 'https' CallbackUrlScheme on Android

Describe the bug

When the callbackUrlScheme is set to either http or https, the package fails to listen to the redirect URL on the Android platform.

To Reproduce

Steps to reproduce the behaviour:

  1. Use the example provided in the package.
  2. Change the callbackUrlScheme in AndroidManifest.xml to either http or https.
  3. Change the callback URL in main.dart to http:/success?code=1337 or https://success?code=1337.
  4. Change the callbackUrlScheme in main.dart to either http or https.
  5. Start the program. Whenever the user clicks authenticate and then clicks sign-in on the login webpage, the package fails to listen to the redirect URL, thus not redirecting the user back to the application.

I have also attempted different combinations, such as setting the callbackUrl to https://success?code=1337 while having the callbackUrlScheme set to http, and vice versa. However, these variations did not yield the desired result.

Expected behaviour

I expected the package to successfully capture the redirect URL when using http or https as the callbackUrlScheme. However, it does not work in this case. Interestingly, if I use any other string as the callbackUrlScheme, such as 'example' or 'foobar', the package successfully captures the redirect URL without any issue.

Screenshots

The following images demonstrate that the redirect URL is ignored and not captured by the package when the callbackUrlScheme is set to http or https:

image image
Pixel 4 API 33 Nexus 5 API 30

As proof, the package works as expected when the callbackUrlScheme is set to any other string (e.g., 'example'):

image image)
Pixel 4 API 33 Nexus 5 API 30

Device

  • Device: Pixel 4 API 33, Nexus 5 API 30 (both running on Android Emulator)
  • flutter_web_auth_2 version: 2.1.5

Checklist

  • [✔] I have read and followed the entire troubleshooting guide and it has not provided the solution I need.
  • [✔ ] I have provided all the information I can (incl. auth URL etc.)

Follow-up Questions

  1. Could there be limitations to how this package works on the Android platform, specifically related to capturing callback URLs that use http or https as the callbackUrlScheme?
  2. Is there any possibility that I am misunderstanding how the package is supposed to be used?

Context

I am testing the usage of http and https as callbackUrlScheme because I am attempting to capture the OAuth token and OAuth verifier returned from the Garmin API during the OAuth 1.0a process. Unfortunately, the Garmin API only allows callback URLs to start with http or https and does not support custom URL schemes.

Implement permissions on exported component.

Is your feature request related to a problem? Please describe.

In our application we started using SonarCloud for monitoring and checking our code quality. The first run we got the next security alert/issue:


Title: Implement permissions on this exported component.

Where:

<activity android:name="com.linusu.flutter_web_auth_2.CallbackActivity" android:exported="true">
   <!-- Implement permissions on this exported component. -->
    <intent-filter android:label="app-name">
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="scheme" />
    </intent-filter>
</activity>

Description:
Once an Android component has been exported, it can be used by attackers to launch malicious actions and might also give access to other components that are not exported.

As a result, sensitive user data can be stolen, and components can be launched unexpectedly.

For this reason, the following components should be protected:

  • Providers
  • Activities
  • Activity-aliases
  • Services

To do so, it is recommended to either set exported to false, add android:readPermission and android:writePermission attributes, or add a <permission> tag.

References:


Describe the solution you'd like

We did a research on our side and we found that:

We are using oauth2_client | Flutter Package, which uses flutter_web_auth_2 | Flutter Package. The docs says it’s necessary to add the following to the AndroidManifest.xml:

<activity android:name="com.linusu.flutter_web_auth_2.CallbackActivity" android:exported="true">
    <intent-filter android:label="app-name">
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="scheme" />
    </intent-filter>
</activity>

This is the cause of the issue, because of android:exported="true". If android:exported="true" is removed the app does not build. Adding android:permission, as suggested by SonarCloud, makes the callback not work without updating the callers of the CallbackActivity.

I dug deep into this but could not find a solution. I think the solution is still to add a tag and then update the callers to start the intent with the permission (according to here under “Securing Activities”). The problem is updating the callers - I was not able to find them. The oauth2_client library uses flutter_web_auth_2, which uses method channels that on Android does intent.launchUrl(context!!, url). I don’t know where the callback activity is called.

This is a Medium severity issue for our app, and it might compromise the data of our customers and the security of our organisation.

Additional context

More info can be found here:

[flutter_web_auth] sign in with goolge faild .

when move to browser i get this Error

Error 400: redirect_uri_mismatch
you can't sign in to this app because it doesn't comply with google's oauth 2.0 policy ,

but i check redirect_uri in my [ firebase auth , google cloud console , my app ] it's a same ,
i can't find the problem ,
should i add Authorized JavaScript origins to google cloud console ,
i used the package from android app .

We need testers!

We are searching for testers for:

The 4.x rewrite

If you want to test the 4.x rewrite, you can already do that by changing the version constraint to flutter_web_auth_2: ^4.0.0-alpha.5
See also here: https://pub.dev/packages/flutter_web_auth_2/versions/4.0.0-alpha.5
Please note the migration guide

Android

I am using this package in production in an app - so I am very sure about its reliability here!

Web

Most of my "quick" tests are done in Edge and Firefox - should also be pretty stable.

Apple

I do not have any devices by Apple. I have no idea how stable the current implementation is. Most testing is necessary here.

Linux

Should be pretty stable, but I only test this occasionally.

Windows

Should be pretty stable, but I only test this occasionally.

Safari shows Pop-up window blocked

When using flutter_web_auth_2: ^2.1.5 and when I call authenticate without passing any contextArgs, the safari blocks open up in a new tab and sayPop-up window blocked.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.