在Android WebView中防止注入攻擊,可以采取以下措施:
WebView webView = findViewById(R.id.webview);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(false);
String html = "<script>alert('XSS Attack');</script>";
HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY).toString();
String userInput = "<script>alert('XSS Attack');</script>";
userInput = userInput.replaceAll("<script>", "").replaceAll("</script>", "");
webView.setWebViewClient(new WebViewClient() {
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
// 檢查請求的URL是否安全
if (!isUrlSafe(request.getUrl().toString())) {
return new WebResourceResponse("text/plain", "utf-8", new ByteArrayInputStream("Not allowed".getBytes()));
}
return super.shouldInterceptRequest(view, request);
}
private boolean isUrlSafe(String url) {
// 實現URL安全檢查邏輯
return true;
}
});
WebSettings webSettings = webView.getSettings();
webSettings.setDomStorageEnabled(false);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.setAcceptThirdPartyCookies(webView, true);
cookieManager.setAcceptHttpCookies(true);
cookieManager.setUseSecureCookies(true);
通過實施這些措施,可以顯著降低Android WebView受到注入攻擊的風險。然而,需要注意的是,沒有任何方法可以完全防止所有的安全威脅,因此應該始終保持警惕并定期更新安全策略。