好的,這花了我很長一段時間,但我能夠發送客戶端證書在Web請求中用於我們的服務器上的客戶端身份驗證。
首先,像Xamarin和.netCore一樣令人敬畏,它們缺少很多方法.net開發人員習慣於。我是不是能夠建立一個跨平臺的要求,將在Android和iOS的工作,如HttpWebRequest的。
對於iOS,我創建了從繼承的自定義類:NSUrlConnectionDataDelegate
然後我重寫:
public override void WillSendRequestForAuthenticationChallenge(NSUrlConnection
connection, NSUrlAuthenticationChallenge challenge)
{
byte[] cert = System.IO.File.ReadAllBytes("clientCertificate.pfx");
NSUrlCredential credential = iSecurity.ImportPK12File(cert, "certPassword");
challenge.Sender.UseCredential(credential, challenge);
}
然後我創建了一個返回憑證類:
//cert is a byte array of a .pfx file included in the resource file
//iSecurity Custom class
NSUrlCredential credential = iSecurity.ImportPK12File(cert, "certpassword");
public static NSUrlCredential ImportPK12File(byte[] fileBytes, string passPhrase)
{
var cert = new X509Certificate2(fileBytes, passPhrase);
var options = NSDictionary.FromObjectAndKey(NSObject.FromObject(passPhrase), SecImportExport.Passphrase);
NSDictionary[] importStatus;
SecStatusCode statusCode = SecImportExport.ImportPkcs12(fileBytes, options, out importStatus);
if(statusCode != SecStatusCode.Success){
throw new Exception("Error importing certificate. ");
}
NSObject obj = importStatus[0]["trust"];
IntPtr secTrustRef = obj.Handle;
var identityHandle = importStatus[0][SecImportExport.Identity];
var identity = new SecIdentity(identityHandle.Handle);
var certificate = new SecCertificate(cert.GetRawCertData());
SecCertificate[] certificates = { certificate };
return NSUrlCredential.FromIdentityCertificatesPersistance(identity, certificates, NSUrlCredentialPersistence.ForSession);
}
您可能還可以重寫此方法併發送vim的信任狀: public override void ReceivedAuthenticationChallenge(NSUrlConnection connection,NSUrlAuthenticationChallenge challenge) base.ReceivedAuthenticationChallenge(connection,challenge); }
,我可能將其移動到那裏,但以火這一關您創建類,從繼承委託:NSUrlConnectionDataDelegate 並添加到您的連接。通過此連接發射的任何請求都覆蓋的方法,並通過認證。
深挖後,雖然客戶端證書可在突變進行設置,它不是在iOS上實現。 – Dys1