Skip to content

[webview_flutter] Support for handling basic authentication requests #5727

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

Merged
merged 38 commits into from
Feb 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
517e9d4
Implement http basic auth
JeroenWeener Aug 10, 2023
967879b
Apply feedback
JeroenWeener Aug 28, 2023
c8624c0
Create HttpAuthHandlerTest.java
JeroenWeener Aug 29, 2023
4f3574d
Format java files
JeroenWeener Aug 29, 2023
1e7f785
Regenerate build_runner files
JeroenWeener Aug 29, 2023
131bc56
Implement feedback
JeroenWeener Sep 11, 2023
bc01be4
Remove redundant key in `Info.plist`
JeroenWeener Sep 11, 2023
67aa00e
Update example apps
JeroenWeener Sep 11, 2023
32496d0
Implement http basic auth
JeroenWeener Aug 10, 2023
aeb8708
Apply feedback
JeroenWeener Aug 28, 2023
fffc4c7
Create HttpAuthHandlerTest.java
JeroenWeener Aug 29, 2023
b455040
Format java files
JeroenWeener Aug 29, 2023
2aa9bfe
Regenerate build_runner files
JeroenWeener Aug 29, 2023
db286ba
Implement feedback
JeroenWeener Sep 11, 2023
467feb3
Remove redundant key in `Info.plist`
JeroenWeener Sep 11, 2023
dad8ae6
Update example apps
JeroenWeener Sep 11, 2023
6f3d802
Merge branch 'webview-auth-request' of https://github.com/andreisas06…
JeroenWeener Nov 1, 2023
0fef591
Add platform interface dev dependency to example
JeroenWeener Nov 1, 2023
b2a4fbb
Merge branch 'main' into webview-auth-request
JeroenWeener Nov 1, 2023
ce35d9b
Update packages/webview_flutter/webview_flutter_platform_interface/li…
bparrishMines Nov 8, 2023
fc32898
Merge branch 'main' of github.com:flutter/packages into webview-auth-…
bparrishMines Nov 8, 2023
4673e65
Merge branch 'webview-auth-request' of github.com:andreisas06/package…
bparrishMines Nov 8, 2023
580521a
Fix some lints, errros and call on errors
bparrishMines Nov 8, 2023
d1f305b
fix lints
bparrishMines Nov 8, 2023
a3f74be
fix tests
bparrishMines Nov 8, 2023
ed3798f
add onProceed and onCancel back
bparrishMines Nov 8, 2023
154c1f8
dont require realm to be nonnull
bparrishMines Nov 8, 2023
3c61dbc
add line back
bparrishMines Nov 8, 2023
7cf0d7e
Merge remote-tracking branch 'upstream/main' into webview-auth-request
JeroenWeener Nov 21, 2023
a21f29a
Update changelogs
JeroenWeener Nov 21, 2023
b109620
Bump dependencies
JeroenWeener Dec 20, 2023
4af593b
Merge remote-tracking branch 'upstream/main' into webview-auth-reques…
JeroenWeener Dec 20, 2023
a578a91
Remove unrelevant changes
JeroenWeener Dec 20, 2023
4b87383
Remove dependency overrides
JeroenWeener Dec 20, 2023
51ebcb3
Merge branch 'main' of github.com:flutter/packages into webview-auth-…
bparrishMines Jan 22, 2024
88f021b
rename test file
bparrishMines Jan 22, 2024
17ea559
fix pubspec and add docs
bparrishMines Jan 22, 2024
dfba830
formatting
bparrishMines Jan 22, 2024
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
3 changes: 2 additions & 1 deletion packages/webview_flutter/webview_flutter/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
## NEXT
## 4.5.0

* Adds support for HTTP basic authentication. See `NavigationDelegate(onReceivedHttpAuthRequest)`.
* Updates support matrix in README to indicate that iOS 11 is no longer supported.
* Clients on versions of Flutter that still support iOS 11 can continue to use this
package with iOS 11, but will not receive any further updates to the iOS implementation.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,25 @@ Future<void> main() async {
request.response.writeln('${request.headers}');
} else if (request.uri.path == '/favicon.ico') {
request.response.statusCode = HttpStatus.notFound;
} else if (request.uri.path == '/http-basic-authentication') {
final List<String>? authHeader =
request.headers[HttpHeaders.authorizationHeader];
if (authHeader != null) {
final String encodedCredential = authHeader.first.split(' ')[1];
final String credential =
String.fromCharCodes(base64Decode(encodedCredential));
if (credential == 'user:password') {
request.response.writeln('Authorized');
} else {
request.response.headers.add(
HttpHeaders.wwwAuthenticateHeader, 'Basic realm="Test realm"');
request.response.statusCode = HttpStatus.unauthorized;
}
} else {
request.response.headers
.add(HttpHeaders.wwwAuthenticateHeader, 'Basic realm="Test realm"');
request.response.statusCode = HttpStatus.unauthorized;
}
} else {
fail('unexpected request: ${request.method} ${request.uri}');
}
Expand All @@ -41,6 +60,7 @@ Future<void> main() async {
final String primaryUrl = '$prefixUrl/hello.txt';
final String secondaryUrl = '$prefixUrl/secondary.txt';
final String headersUrl = '$prefixUrl/headers';
final String basicAuthUrl = '$prefixUrl/http-basic-authentication';

testWidgets('loadRequest', (WidgetTester tester) async {
final Completer<void> pageFinished = Completer<void>();
Expand All @@ -52,7 +72,6 @@ Future<void> main() async {
unawaited(controller.loadRequest(Uri.parse(primaryUrl)));

await tester.pumpWidget(WebViewWidget(controller: controller));

await pageFinished.future;

final String? currentUrl = await controller.currentUrl();
Expand Down Expand Up @@ -761,6 +780,54 @@ Future<void> main() async {

await expectLater(urlChangeCompleter.future, completion(secondaryUrl));
});

testWidgets('can receive HTTP basic auth requests',
(WidgetTester tester) async {
final Completer<void> authRequested = Completer<void>();
final WebViewController controller = WebViewController();

unawaited(
controller.setNavigationDelegate(
NavigationDelegate(
onHttpAuthRequest: (HttpAuthRequest request) =>
authRequested.complete(),
),
),
);

await tester.pumpWidget(WebViewWidget(controller: controller));

unawaited(controller.loadRequest(Uri.parse(basicAuthUrl)));

await expectLater(authRequested.future, completes);
});

testWidgets('can authenticate to HTTP basic auth requests',
(WidgetTester tester) async {
final WebViewController controller = WebViewController();
final Completer<void> pageFinished = Completer<void>();

unawaited(
controller.setNavigationDelegate(
NavigationDelegate(
onHttpAuthRequest: (HttpAuthRequest request) => request.onProceed(
const WebViewCredential(
user: 'user',
password: 'password',
),
),
onPageFinished: (_) => pageFinished.complete(),
onWebResourceError: (_) => fail('Authentication failed'),
),
),
);

await tester.pumpWidget(WebViewWidget(controller: controller));

unawaited(controller.loadRequest(Uri.parse(basicAuthUrl)));

await expectLater(pageFinished.future, completes);
});
});

testWidgets('target _blank opens in same window',
Expand Down
98 changes: 98 additions & 0 deletions packages/webview_flutter/webview_flutter/example/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,9 @@ Page resource error:
onUrlChange: (UrlChange change) {
debugPrint('url change to ${change.url}');
},
onHttpAuthRequest: (HttpAuthRequest request) {
openDialog(request);
},
),
)
..addJavaScriptChannel(
Expand Down Expand Up @@ -226,6 +229,62 @@ Page resource error:
child: const Icon(Icons.favorite),
);
}

Future<void> openDialog(HttpAuthRequest httpRequest) async {
final TextEditingController usernameTextController =
TextEditingController();
final TextEditingController passwordTextController =
TextEditingController();

return showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return AlertDialog(
title: Text('${httpRequest.host}: ${httpRequest.realm ?? '-'}'),
content: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
TextField(
decoration: const InputDecoration(labelText: 'Username'),
autofocus: true,
controller: usernameTextController,
),
TextField(
decoration: const InputDecoration(labelText: 'Password'),
controller: passwordTextController,
),
],
),
),
actions: <Widget>[
// Explicitly cancel the request on iOS as the OS does not emit new
// requests when a previous request is pending.
TextButton(
onPressed: () {
httpRequest.onCancel();
Navigator.of(context).pop();
},
child: const Text('Cancel'),
),
TextButton(
onPressed: () {
httpRequest.onProceed(
WebViewCredential(
user: usernameTextController.text,
password: passwordTextController.text,
),
);
Navigator.of(context).pop();
},
child: const Text('Authenticate'),
),
],
);
},
);
}
}

enum MenuOptions {
Expand All @@ -243,6 +302,7 @@ enum MenuOptions {
transparentBackground,
setCookie,
logExample,
basicAuthentication,
}

class SampleMenu extends StatelessWidget {
Expand Down Expand Up @@ -288,6 +348,8 @@ class SampleMenu extends StatelessWidget {
_onSetCookie();
case MenuOptions.logExample:
_onLogExample();
case MenuOptions.basicAuthentication:
_promptForUrl(context);
}
},
itemBuilder: (BuildContext context) => <PopupMenuItem<MenuOptions>>[
Expand Down Expand Up @@ -348,6 +410,10 @@ class SampleMenu extends StatelessWidget {
value: MenuOptions.logExample,
child: Text('Log example'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.basicAuthentication,
child: Text('Basic Authentication Example'),
),
],
);
}
Expand Down Expand Up @@ -501,6 +567,38 @@ class SampleMenu extends StatelessWidget {

return webViewController.loadHtmlString(kLogExamplePage);
}

Future<void> _promptForUrl(BuildContext context) {
final TextEditingController urlTextController = TextEditingController();

return showDialog<String>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Input URL to visit'),
content: TextField(
decoration: const InputDecoration(labelText: 'URL'),
autofocus: true,
controller: urlTextController,
),
actions: <Widget>[
TextButton(
onPressed: () {
if (urlTextController.text.isNotEmpty) {
final Uri? uri = Uri.tryParse(urlTextController.text);
if (uri != null && uri.scheme.isNotEmpty) {
webViewController.loadRequest(uri);
Navigator.pop(context);
}
}
},
child: const Text('Visit'),
),
],
);
},
);
}
}

class NavigationControls extends StatelessWidget {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ dependencies:
# The example app is bundled with the plugin so we use a path dependency on
# the parent directory to use the current plugin's version.
path: ../
webview_flutter_android: ^3.12.0
webview_flutter_wkwebview: ^3.9.0
webview_flutter_android: ^3.13.0
webview_flutter_wkwebview: ^3.10.0

dev_dependencies:
build_runner: ^2.1.5
Expand All @@ -27,7 +27,7 @@ dev_dependencies:
sdk: flutter
integration_test:
sdk: flutter
webview_flutter_platform_interface: ^2.3.0
webview_flutter_platform_interface: ^2.7.0

flutter:
uses-material-design: true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,4 +116,9 @@ class FakeNavigationDelegate extends PlatformNavigationDelegate {

@override
Future<void> setOnUrlChange(UrlChangeCallback onUrlChange) async {}

@override
Future<void> setOnHttpAuthRequest(
HttpAuthRequestCallback handler,
) async {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ class NavigationDelegate {
///
/// {@template webview_fluttter.NavigationDelegate.constructor}
/// `onUrlChange`: invoked when the underlying web view changes to a new url.
/// `onHttpAuthRequest`: invoked when the web view is requesting authentication.
/// {@endtemplate}
NavigationDelegate({
FutureOr<NavigationDecision> Function(NavigationRequest request)?
Expand All @@ -48,6 +49,7 @@ class NavigationDelegate {
void Function(int progress)? onProgress,
void Function(WebResourceError error)? onWebResourceError,
void Function(UrlChange change)? onUrlChange,
void Function(HttpAuthRequest request)? onHttpAuthRequest,
}) : this.fromPlatformCreationParams(
const PlatformNavigationDelegateCreationParams(),
onNavigationRequest: onNavigationRequest,
Expand All @@ -56,6 +58,7 @@ class NavigationDelegate {
onProgress: onProgress,
onWebResourceError: onWebResourceError,
onUrlChange: onUrlChange,
onHttpAuthRequest: onHttpAuthRequest,
);

/// Constructs a [NavigationDelegate] from creation params for a specific
Expand Down Expand Up @@ -98,6 +101,7 @@ class NavigationDelegate {
void Function(int progress)? onProgress,
void Function(WebResourceError error)? onWebResourceError,
void Function(UrlChange change)? onUrlChange,
void Function(HttpAuthRequest request)? onHttpAuthRequest,
}) : this.fromPlatform(
PlatformNavigationDelegate(params),
onNavigationRequest: onNavigationRequest,
Expand All @@ -106,6 +110,7 @@ class NavigationDelegate {
onProgress: onProgress,
onWebResourceError: onWebResourceError,
onUrlChange: onUrlChange,
onHttpAuthRequest: onHttpAuthRequest,
);

/// Constructs a [NavigationDelegate] from a specific platform implementation.
Expand All @@ -119,6 +124,7 @@ class NavigationDelegate {
this.onProgress,
this.onWebResourceError,
void Function(UrlChange change)? onUrlChange,
HttpAuthRequestCallback? onHttpAuthRequest,
}) {
if (onNavigationRequest != null) {
platform.setOnNavigationRequest(onNavigationRequest!);
Expand All @@ -138,6 +144,9 @@ class NavigationDelegate {
if (onUrlChange != null) {
platform.setOnUrlChange(onUrlChange);
}
if (onHttpAuthRequest != null) {
platform.setOnHttpAuthRequest(onHttpAuthRequest);
}
}

/// Implementation of [PlatformNavigationDelegate] for the current platform.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

export 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart'
show
HttpAuthRequest,
JavaScriptConsoleMessage,
JavaScriptLogLevel,
JavaScriptMessage,
Expand All @@ -24,6 +25,7 @@ export 'package:webview_flutter_platform_interface/webview_flutter_platform_inte
WebResourceErrorCallback,
WebResourceErrorType,
WebViewCookie,
WebViewCredential,
WebViewPermissionResourceType,
WebViewPlatform;

Expand Down
8 changes: 4 additions & 4 deletions packages/webview_flutter/webview_flutter/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ name: webview_flutter
description: A Flutter plugin that provides a WebView widget on Android and iOS.
repository: https://github.com/flutter/packages/tree/main/packages/webview_flutter/webview_flutter
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+webview%22
version: 4.4.4
version: 4.5.0

environment:
sdk: ">=3.0.0 <4.0.0"
Expand All @@ -19,9 +19,9 @@ flutter:
dependencies:
flutter:
sdk: flutter
webview_flutter_android: ^3.12.0
webview_flutter_platform_interface: ^2.6.0
webview_flutter_wkwebview: ^3.9.0
webview_flutter_android: ^3.13.0
webview_flutter_platform_interface: ^2.7.0
webview_flutter_wkwebview: ^3.10.0

dev_dependencies:
build_runner: ^2.1.5
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,18 @@ void main() {

verify(delegate.platform.setOnUrlChange(onUrlChange));
});

test('onHttpAuthRequest', () {
WebViewPlatform.instance = TestWebViewPlatform();

void onHttpAuthRequest(HttpAuthRequest request) {}

final NavigationDelegate delegate = NavigationDelegate(
onHttpAuthRequest: onHttpAuthRequest,
);

verify(delegate.platform.setOnHttpAuthRequest(onHttpAuthRequest));
});
});
}

Expand Down
Loading