2007年6月1日

自訂的SSL驗證程序過不去的解決方法

The Remote Certificate Is Invalid According To the Validation Procedure (C#)

One way to secure XML web services is using SSL. If you install a certificate that has not been issued by a trusted certification authority on the web site hosting the web service and you consume the web service from a .NET application, then you would probably get an AuthenticationException warning you that "the remote certificate is invalid according to the validation procedure". This happens because the default certificate policy only allows valid certificates and valid certificates that have expired. This post explains how to implement a custom certificate policy that determines whether the specified certificate is accepted for authentication.

You may use the CertificatePolicy property of the ServicePointManager class. When this property is set to an ICertificatePolicy interface object, the ServicePointManager uses the certificate policy defined in that instance instead of the default certificate policy. However as of version 2.0 of the .NET Framework the CertificatePolicy property of the ServicePointManager class is obsolete.

The suggested approach is using the ServerCertificateValidationCallback property of the ServicePointManager class.

1) Implement your custom certificate policy in a method that returns a Boolean value. The signature of the method must match the signature of the RemoteCertificateValidationCallback delegate. This delegate determines whether the authentication is allowed to succeed based on the Boolean value returned by your method. The method in the following code example simply allows all certificates.



using System;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

// ...

public static bool ValidateServerCertificate(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}


2) Create the RemoteCertificateValidationCallback delegate using the method defined in the preceding code example and assign it to the ServerCertificateValidationCallback property of the ServicePointManager class.

using System.Net;
using System.Net.Security;

// ...

ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);

沒有留言:

張貼留言