在Android WebView中防止跨站腳本攻擊(XSS)可以采取以下措施:
WebView webView = findViewById(R.id.webview);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
shouldInterceptRequest
方法過濾惡意資源:通過重寫shouldInterceptRequest
方法,可以攔截WebView加載的資源,檢查其內容是否包含惡意腳本,并進行相應的處理,如刪除或替換。webView.setWebViewClient(new WebViewClient() {
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
String url = request.getUrl().toString();
// 檢查URL是否包含惡意資源,如包含<script>標簽等
if (isMalicious(url)) {
// 返回一個空的響應,阻止加載惡意資源
return new WebResourceResponse("text/plain", "utf-8", new ByteArrayInputStream("".getBytes()));
}
return super.shouldInterceptRequest(view, request);
}
});
String htmlContent = "<html><head></head><body><script>alert('XSS');</script></body></html>";
HtmlCompat.fromHtml(htmlContent, HtmlCompat.FROM_HTML_MODE_LEGACY).toString();
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.setAcceptThirdPartyCookies(webView, true);
cookieManager.setHttpOnlyCookiesForDomain("example.com", true);
// 獲取默認的TrustManager
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init((KeyStore) null);
// 創建SSLSocketFactory,使用自定義的TrustManager
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
// 設置WebView的SSLSocketFactory
webView.setWebViewClient(new WebViewClient() {
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
// 接受所有證書,用于測試目的
handler.proceed();
}
});
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
webView.setSSLSocketFactory(sslContext.getSocketFactory());
通過采取這些措施,可以有效地防止Android WebView中的跨站腳本攻擊。