Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Silent Authentication Using Hidden Iframe #88

Merged
merged 1 commit into from
Dec 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 18 additions & 7 deletions flutter_web_auth_2/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -156,22 +156,33 @@ On the Web platform, an endpoint must be created that captures the callback URL
<title>Authentication complete</title>
<p>Authentication is complete. If this does not happen automatically, please close the window.</p>
<script>
if (window.opener) {
window.opener.postMessage({
function postAuthenticationMessage() {
const message = {
'flutter-web-auth-2': window.location.href
}, window.location.origin);
} else {
localStorage.setItem('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();
}
}
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).

If you want to pass additional parameters to the URL open call, you can do so in the `authenticate` function using the parameter `windowName` from the options.
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

Expand Down
38 changes: 24 additions & 14 deletions flutter_web_auth_2/example/web/auth.html
Original file line number Diff line number Diff line change
@@ -1,16 +1,26 @@
<!DOCTYPE html>
<title>Authentication complete</title>
<p>Authentication will complete in around two seconds. If this does not happen automatically, please
close the window.
<script>
setTimeout(function(){
if (window.opener) {
window.opener.postMessage({
<html>
<head>
<title>Authentication complete</title>
</head>
<body>
<p>Authentication will complete in around two seconds. If this does not happen automatically, please close the window.</p>
<script>
setTimeout(function() {
const message = {
'flutter-web-auth-2': window.location.href
}, window.location.origin);
} else {
localStorage.setItem('flutter-web-auth-2', window.location.href);
}
window.close();
}, 2000);
</script>
};

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();
}
}, 2000);
</script>
</body>
</html>
12 changes: 12 additions & 0 deletions flutter_web_auth_2/lib/src/options.dart
Original file line number Diff line number Diff line change
Expand Up @@ -84,13 +84,23 @@ class FlutterWebAuth2Options {
/// will be displayed using a `HttpServer`.
final String landingPageHtml;

/// **Only has an effect on Web!**
/// When set to true, the authentication URL will be loaded in a hidden iframe
/// instead of opening a new window or tab. This is primarily used for silent
/// authentication processes where a full-page redirect is not desirable.
/// It allows for a seamless user experience by performing the authentication
/// in the background. This approach is useful for token refreshes or for
/// maintaining user sessions without explicit user interaction.
final bool silentAuth;

const FlutterWebAuth2Options({
bool? preferEphemeral,
this.debugOrigin,
int? intentFlags,
this.windowName,
int? timeout,
String? landingPageHtml,
this.silentAuth = false,
}) : preferEphemeral = preferEphemeral ?? false,
intentFlags = intentFlags ?? defaultIntentFlags,
timeout = timeout ?? 5 * 60,
Expand All @@ -104,6 +114,7 @@ class FlutterWebAuth2Options {
windowName: json['windowName'],
timeout: json['timeout'],
landingPageHtml: json['landingPageHtml'],
silentAuth: json['silentAuth'],
);

Map<String, dynamic> toJson() => {
Expand All @@ -113,5 +124,6 @@ class FlutterWebAuth2Options {
'windowName': windowName,
'timeout': timeout,
'landingPageHtml': landingPageHtml,
'silentAuth': silentAuth,
};
}
48 changes: 44 additions & 4 deletions flutter_web_auth_2/lib/src/web.dart
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,50 @@ class FlutterWebAuth2WebPlugin extends FlutterWebAuth2Platform {
}) async {
final parsedOptions = FlutterWebAuth2Options.fromJson(options);

await launchUrl(
Uri.parse(url),
webOnlyWindowName: parsedOptions.windowName,
);
if (parsedOptions.silentAuth) {
final authIframe = IFrameElement()
..src = url
..style.display = 'none';

document.body?.append(authIframe);

final completer = Completer<String>();
StreamSubscription? messageSubscription;
Timer? responseTimeoutTimer;

messageSubscription = window.onMessage.listen((messageEvent) {
if (messageEvent.origin ==
(parsedOptions.debugOrigin ?? Uri.base.origin)) {
final flutterWebAuthMessage = messageEvent.data['flutter-web-auth-2'];
if (flutterWebAuthMessage is String) {
authIframe.remove();
completer.complete(flutterWebAuthMessage);
responseTimeoutTimer?.cancel();
messageSubscription?.cancel();
}
}
});

// Add a timeout for the iframe response
responseTimeoutTimer =
Timer(Duration(seconds: parsedOptions.timeout), () {
authIframe.remove();
messageSubscription?.cancel();
completer.completeError(
PlatformException(
code: 'timeout',
message: 'Timeout waiting for the iframe response',
),
);
});

return completer.future;
} else {
await launchUrl(
Uri.parse(url),
webOnlyWindowName: parsedOptions.windowName,
);
}

// Remove the old record if it exists
const storageKey = 'flutter-web-auth-2';
Expand Down