【问题标题】:Xamarin way to open self signed certificate webpage in UIWebViewXamarin 在 UIWebView 中打开自签名证书网页的方式
【发布时间】:2014-11-11 13:29:27
【问题描述】:
正如问题标题所述,我想在 UIWebview (Xamarin.iOS) 中打开一个自签名网页
默认情况下,自签名网页不会加载到 UIWebView 中。
解决方案的重要要求:
- 当我想将应用程序提交到 Apple 应用商店时,Apple 应该接受它(因此不适合自定义 NSUrlRequest)。
- 它应该能正确加载 css 和 javascript。
我在 stackoverflow 上找到了一个可能的解决方案,但这是针对本机 iOS 的。
https://stackoverflow.com/a/11664147
我还想知道上述解决方案是否需要使用 NSUrlConnectionDelegate 登录。
理想的解决方案应该是用户可以使用 UIWebView 自己填写凭据。
有人可以为此提供 Xamarin 解决方案吗?我自己尝试过,但无法正常工作。
提前感谢您的帮助。
【问题讨论】:
标签:
ios
uiwebview
xamarin.ios
xamarin
ssl-certificate
【解决方案1】:
我知道这是一篇很老的帖子,但这是一个很有趣的问题,所以我不得不试一试。因此,如果您仍然需要它(很可能不需要)或者如果有人找到这篇文章,这里有一个支持自签名的原生 UIWebView 的移植版本。它可以用作常规 UIWebView,但它需要一个主机名作为附加参数,它应该是应该禁用证书检查的页面的主机名。
public class InsecureWebView : UIWebView, INSUrlConnectionDataDelegate, IUIWebViewDelegate
{
public InsecureWebView(string baseUrl) : base()
{
Setup (baseUrl);
}
public InsecureWebView(CoreGraphics.CGRect rect, string baseUrl) : base(rect)
{
Setup (baseUrl);
}
public InsecureWebView(NSCoder coder, string baseUrl) : base(coder)
{
Setup (baseUrl);
}
public InsecureWebView(NSObjectFlag t, string baseUrl) : base(t)
{
Setup (baseUrl);
}
public InsecureWebView(IntPtr handler, string baseUrl) : base(handler)
{
Setup (baseUrl);
}
string baseUrl = null;
bool authenticated;
NSUrlRequest failedRequest;
private void Setup(string baseUrl)
{
this.Delegate = this;
this.baseUrl = baseUrl;
}
[Foundation.Export ("webView:shouldStartLoadWithRequest:navigationType:")]
public bool ShouldStartLoad (UIKit.UIWebView webView, Foundation.NSUrlRequest request, UIKit.UIWebViewNavigationType navigationType)
{
var result = authenticated;
if (!authenticated) {
failedRequest = request;
NSUrlConnection.FromRequest (request, this);
}
return result;
}
[Foundation.Export ("connection:willSendRequestForAuthenticationChallenge:")]
public void WillSendRequestForAuthenticationChallenge (NSUrlConnection connection, NSUrlAuthenticationChallenge challenge)
{
if (challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodServerTrust) {
var baseUrl = new NSUrl (this.baseUrl);
if (challenge.ProtectionSpace.Host == baseUrl.Host) {
challenge.Sender.UseCredential (NSUrlCredential.FromTrust (challenge.ProtectionSpace.ServerSecTrust), challenge);
}
}
challenge.Sender.ContinueWithoutCredential (challenge);
}
[Foundation.Export ("connection:didReceiveResponse:")]
public void DidReceivedResponse(NSUrlConnection connection, NSUrlResponse response)
{
authenticated = true;
connection.Cancel ();
LoadRequest (failedRequest);
}
}