前言
为了提高应用的安全性,有时候我们需要过滤WebView的请求,从而达到并不是信任所有的请求,可以防止在App中打开非正常链接或者屏蔽广告
1.过滤名单
如果你的App有比较严格的安全需求,则只需要信任自己定义的信任列表,把列表之外的路径都不让其加载,如果你的App中会加载大量的外部网页默认信任大部分网页则只需要添加黑名单,依需求而定
val hostPattern = arrayListOf(
"^.+\\.baidu\\.com",
"^.+\\.youcompany\\.com"
)
需要注意一点,为了增强匹配的安全性我们可以使用正则去进行匹配,正则中"."表示任何所以我们需要加上转义字符
fun checkIsTrustUrl(path:String?,pattern: List<String>):Boolean{
try{
val url = URL(path)
pattern.forEach {
if(Pattern.compile(it).matcher(url.host).find()){
return true
}
}
}catch (e: MalformedURLException){
if(BuildConfig.DEBUG){
Log.d("SecurityHelper","$path ${e.message}")
}
}
return false
}
1.在WebView设置中拦截Web请求
shouldInterceptRequest函数会拦截所有经过的web资源资源请求,当没有通过我们的名单校验时,则返回一个不返回任何资源的WebResourceResponse对象,意味着不加载此资源,这里要注意就是shouldInterceptRequest函数的返回值不要直接返回null,那意味着交给了webView自己处理起不到拦截的作用
object : WebViewClient(){
override fun shouldInterceptRequest(
view: WebView?,
url:String
): WebResourceResponse? {
if(!SecurityHelper.checkIsTrustUrl(url,SecurityHelper.hostPattern)){
return WebResourceResponse(null,null,null)
}
return super.shouldInterceptRequest(view, url)
}
}
欢迎关注Mike的简书
Android 知识整理
网友评论