我正在尝试使用WebView在Android上进行双向mTls身份验证。我在Android钥匙串中安装了客户端证书,并覆盖了如下的onReceivedClientCertRequest方法,以便从Android钥匙串中获取客户端证书:
@Override
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void onReceivedClientCertRequest(WebView view, ClientCertRequest request) {
Log.d("MC-999","onReceivedClientCertRequest");
Log.d("MC-999", request.getHost());
Log.d("MC-999", request.getPrincipals()[0].getName());
((WebViewActivity) mContext).selectClientCert(request);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void selectClientCert(ClientCertRequest request) {
Log.d("MC-999","Select client cert.");
mRequest = request;
KeyChain.choosePrivateKeyAlias(this,
this, // Callback
request.getKeyTypes(),
request.getPrincipals(), // issuers.
request.getHost(), // host
request.getPort(), // port
"");
}
@Override
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void alias(@Nullable String alias) {
if (alias != null) {
X509Certificate[] certChain = getCertificateChain(alias);
PrivateKey privateKey = getPrivateKey(alias);
mRequest.proceed(privateKey, certChain);
} else {
mRequest.ignore();
}
}
问题: onReceivedClientCertRequest方法仅在第一次调用一次。此后不调用。我必须重新启动设备以确保再次请求客户端证书。该文档还指出
“ 如果已调用ClientCertRequest#proceed或ClientCertRequest#cancel并且未针对同一主机和端口对再次调用onReceivedClientCertRequest(),则Webview会将响应存储在内存中(在应用程序生命期内)。“
我的问题是,如果用户第一次选择错误的证书,则WebView随后会继续使用它。方法 mWebView.clearSslPreferences(); 似乎无法清除sslContext。
如果遇到SSL错误,是否可以忘记用户的证书选择?