Develop secure WebView2 apps

The WebView2 control allows developers to host web content in the native applications. When used correctly, hosting web content offers several advantages, such as using web-based UI, accessing features of the web platform, sharing code cross-platform, and so on. To avoid vulnerabilities that can arise from hosting web content, make sure to design your WebView2 application to closely monitor interactions between the web content and the host application.

  • Treat all web content as insecure:

    • Validate web messages and host object parameters before consuming them, because web messages and parameters can be malformed (unintentionally or maliciously) and can cause the app to behave unexpectedly.

    • Always check the origin of the document that's running inside WebView2, and assess the trustworthiness of the content.

  • Design specific web messages and host object interactions, instead of using generic proxies.

  • Set the following options to restrict web content functionality, by modifying ICoreWebView2Settings (Win32) or CoreWebView2Settings (.NET):

    • Set AreHostObjectsAllowed to false, if you don't expect the web content to access host objects.

    • Set IsWebMessageEnabled to false, if you don't expect the web content to post web messages to your native application.

    • Set IsScriptEnabled to false, if you don't expect the web content to run scripts (for example, when showing static HTML content).

    • Set AreDefaultScriptDialogsEnabled to false, if you don't expect the web content to show alert or prompt dialogs.

  • Update settings based on the origin of the new page:

    • To prevent your application from navigating to certain pages, use the NavigationStarting and FrameNavigationStarting events to check page or frame navigation, and then conditionally block the navigation.

    • When navigating to a new page, you may need to adjust the property values on ICoreWebView2Settings (Win32) or CoreWebView2Settings (.NET), as previously described.

  • When navigating to a new document, use the ContentLoading event and RemoveHostObjectFromScript to remove exposed host objects.

  • WebView2 cannot be run as a system user. This restriction blocks scenarios such as building a Credential Provider.