flutter_web_auth_2 6.0.0-alpha.11
flutter_web_auth_2: ^6.0.0-alpha.11 copied to clipboard
Flutter plugin for authenticating a user with a web service.
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.
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 Auth Tab 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: ^6.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 (Google multiple scopes): To use multiple scopes with Google, you need to encode them as a single string, separated by spaces (%20). For example, scope: 'email https://www.googleapis.com/auth/userinfo.profile'. Here is a list of all supported scopes.
Note (ephemeral auth): Due to a known Chrome bug, when setting preferEphemeral: true on Android with Chrome < 141, the package will launch an auth session with older implementation to avoid crashes.
Note (Android Auth Tabs): The package uses an Auth Tab when the selected browser reports support. If the Auth Tab refuses the flow because redirect verification fails or times out, the package retries once with a regular Custom Tab. Set preferAuthTabs: false in FlutterWebAuth2Options to always use a regular Custom Tab.
Migration #
Upgrading to 6.x #
The following constraints have been added in 6.0.0:
- Dart SDK
>=3.13.0and Flutter>=3.47.0is now required - Migrated to
material_uipackage - Built-in Kotlin is fully supported (and AGP
9.xas well as Gradle9.x) - If you do not need the web view approach on Linux or Windows at all, you can follow the unlink instructions, which could make your build faster and lighter
- Upgraded
webdependency fully to1.x(that is,0.xis no longer supported) - Upgraded
window_to_frontdependency fully to1.x(that is,0.xis no longer supported) - Upgraded
desktop_webview_windowdependency fully to0.4.x(that is,0.3.xand below is no longer supported) - Renamed:
cleanUpDanglingCalls->clearAllDanglingCalls
Upgrading to 5.x #
The following constraints have been added in 5.0.0:
- The existing Android approach has been replaced with a new (improved) one (no migration necessary; is automatically used)
- Android now uses Auth Tab:
httpsHostandhttpsPathare now required on Android if you are using ahttpsincallbackUrlScheme - On Android, issues with
taskAffinitys have been fixed and it is strongly advised to setandroid:taskAffinity=""for all exportedActivitys (this usually includes yourMainActivityandflutter_web_auth_2'sCallbackActivity) - Dart SDK
>=3.5.0is now required (due to migration to melos7.x) - If you want ephemeral authentication on Android, use
preferEphemeralinstead ofephemeralIntentFlagsasintentFlagshave other influences now
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"
android:taskAffinity="">
<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.
To learn more about setting up Android App Links, see Flutter's guide.
iOS / macOS (Apple platforms) #
For custom callback schemes (for example myapp://callback), just use this library as usual.
If you use https as callbackUrlScheme (Universal Links), additional Apple platform setup is required:
- Configure Associated Domains in your app entitlements.
- Add your domain using the
webcredentialsservice type (for example:webcredentials:example.com). - Host a valid
apple-app-site-association(AASA) file for that domain, with your app identifier. - Pass
httpsHostandhttpsPathinFlutterWebAuth2Options.
Example:
final result = await FlutterWebAuth2.authenticate(
url: "https://my-custom-app.com/connect",
callbackUrlScheme: "https",
options: const FlutterWebAuth2Options(
httpsHost: "my-custom-app.com",
httpsPath: "/oauth",
),
);
If this setup is incomplete, Apple can reject the auth callback and you'll receive a PlatformException from native code. Check PlatformException.details (domain, code, description) for the exact reason.
To learn more about setting up Universal Links, see Flutter's guide.
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.
Without the webview
If you only use useWebview: false, you can avoid linking WebKitGTK on Linux and WebView2 on Windows by replacing the webview package with a stub:
dependency_overrides:
flutter_web_auth_2_desktop_webview:
git:
url: https://github.com/ThexXTURBOXx/flutter_web_auth_2
ref: <flutter_web_auth_2 version>
path: flutter_web_auth_2_desktop_webview_stub
Explicitly using the stub together with useWebview: true throws a StateError on Windows and Linux. You cannot use the webview approach without the required dependencies.
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 #
- Stop the application if it is running.
- Run the following commands:
flutter cleanflutter pub upgrade
- Rerun the application after executing the above commands. Sometimes, they work wonders!
Troubleshooting callbackUrlScheme #
callbackUrlSchememust 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 arecallback-scheme,another.scheme,examplescheme - Examples of INVALID
callbackUrlSchemes arecallback_scheme,1another.scheme,exampleScheme
Troubleshooting Flutter App #
-
You have to tell the
FlutterWebAuth2.authenticatefunction what yourcallbackUrlSchemeis. -
Example: If your
callbackUrlSchemeisvalid-callback-scheme, your dart code will look likeimport '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.xmlto include thecom.linusu.flutter_web_auth_2.CallbackActivityactivity, 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" android:taskAffinity=""> <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.xmlwith VALIDcallbackUrlScheme. In the example below ourcallbackUrlSchemeisvalid-callback-scheme.<manifest> <application> <activity android:name="com.linusu.flutter_web_auth_2.CallbackActivity" android:exported="true" android:taskAffinity=""> <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 addandroid:exported="true"to thecom.linusu.flutter_web_auth.CallbackActivityactivity in yourAndroidManifest.xmlfile.- <activity android:name="com.linusu.flutter_web_auth_2.CallbackActivity"> + <activity + android:name="com.linusu.flutter_web_auth_2.CallbackActivity" + android:exported="true" + android:taskAffinity=""> -
If you want to have a callback URL with
httporhttpsscheme, you also need to specify a host etc. See c:geo as an example for this. -
In older versions of this package, there was a known problem with task affinities and launch modes (see #113). In order to ensure that
flutter_web_auth_2works correctly on these versions (prior to5.0.0-alpha.2), setandroid:launchMode="singleTop"and remove anyandroid:taskAffinityentries. This configuration is guaranteed to work. In newer versions, this should not cause problems!
Troubleshooting OAuth redirects #
- Your OAuth Provider must redirect to the valid
callbackUrlScheme+://. This mean if yourcallbackUrlSchemeisvalidscheme, your OAuth Provider must redirect tovalidscheme:// - Example with
PHP:<?php header("Location: validscheme://?data1=value1&data2=value2");
Troubleshooting Native Errors (iOS/macOS) #
On iOS and macOS, native authentication failures are forwarded as PlatformException values.
Besides code and message, the details map contains:
domaincodedescription
This is especially useful for https callback issues on Apple platforms (for example, Associated Domains / webcredentials setup problems).
import 'package:flutter/services.dart';
try {
final result = await FlutterWebAuth2.authenticate(
url: authUrl,
callbackUrlScheme: 'https',
options: const FlutterWebAuth2Options(
httpsHost: 'example.com',
httpsPath: '/oauth',
),
);
// use result
} on PlatformException catch (e) {
final details = e.details is Map ? e.details as Map : const {};
final nativeDomain = details['domain'];
final nativeCode = details['code'];
final nativeDescription = details['description'];
// Log or show the native diagnostics here.
}
Troubleshooting HTML redirects #
-
If you are using HTML hyperlinks, it must be a valid
callbackUrlScheme+://. This means that if yourcallbackUrlSchemeiscustomappname, your HTML hyperlink should becustomappname:// -
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=valuetype of data after yourcallbackUrlScheme+://+? -
Example to pass
access-tokento 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-tokenanduser_idto 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.
