Intercepting requests from BlazorWebView
See original GitHub issueDescription
In the documentation surrounding Blazor Hybrid apps with .NET MAUI it is stated that it not recommended to expose the access token to JavaScript running inside of the WebView. Instead it is suggested that network requests are intercepted so that the access token can be injected by the native app. This indeed seems to me to be the most secure way of doing it.
However it doesn’t seem there’s a good way to do this with the current API’s. I’ve managed to get something to work on Android by wrapping the WebViewClient that is injected by the BlazorWebView control and overriding a couple of methods there, but this feels brittle as the WebViewClient provided by Blazor might override additional methods in the future. On iOS I haven’t found a solution that works so far although I haven’t looked into it deeply enough yet.
Public API Changes
var webView = new BlazorWebView();
webView.OnRequest += (sender, args) =>
{
args.RequestHeaders.Add("Authorization", "Bearer " + token);
}
Intended Use-Case
It would be great if the BlazorWebView had some API that would allow us to intercept requests and inject additional request headers depending on the destination of the request for example. This would allow non-Blazor JavaScript to run inside of a Blazor Hybrid app while communicating with a backend somewhere that requires authentication.
Issue Analytics
- State:
- Created 10 months ago
- Reactions:8
- Comments:11 (1 by maintainers)

Top Related StackOverflow Question
@mcl-sz Rather than replacing the
WebViewClient, try wrapping it instead. So I created a derivedWebViewClientclass that accepts aWebViewClientas a constructor parameter and in theShoudlInterceptRequest()method I do my custom logic if needed and call the innerWebViewClient(if needed). That way the Blazor specific logic should still work.@inetzo I did manage to get something working by injecting a custom
WebViewClienton Android and a customUrlSchemeHandleron iOS through theBlazorWebViewInitializedandBlazorWebViewInitializing. Unfortunately I found out that on Android you can implement theShouldInterceptRequestmethod, but it doesn’t give you access to the request body so you cannot perform a full request which is quite limiting IMHO. However, that is a limitation of the Android platform, not so much of .NET MAUI nor Blazor.