Joe*_*ang 121 c# ssl certificate httpwebrequest
我正在尝试找到一种方法来在请求Https资源时忽略证书检查,到目前为止,我在互联网上找到了一些有用的文章.
但我还是有一些问题.请查看我的代码.我只是不明白代码ServicePointManager.ServerCertificateValidationCallback是什么意思.
何时调用此委托方法?还有一个问题,我应该在哪个地方编写这段代码?在ServicePointManager.ServerCertificateValidationCallback执行之前还是之前Stream stream = request.GetRequestStream()?
public HttpWebRequest GetRequest()
{
CookieContainer cookieContainer = new CookieContainer();
// Create a request to the server
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_remoteUrl);
#region Set request parameters
request.Method = _context.Request.HttpMethod;
request.UserAgent = _context.Request.UserAgent;
request.KeepAlive = true;
request.CookieContainer = cookieContainer;
request.PreAuthenticate = true;
request.AllowAutoRedirect = false;
#endregion
// For POST, write the post data extracted from the incoming request
if (request.Method == "POST")
{
Stream clientStream = _context.Request.InputStream;
request.ContentType = _context.Request.ContentType;
request.ContentLength = clientStream.Length;
ServicePointManager.ServerCertificateValidationCallback = delegate(
Object obj, X509Certificate certificate, X509Chain chain,
SslPolicyErrors errors)
{
return (true);
};
Stream stream = request.GetRequestStream();
....
}
....
return request;
}
}
Run Code Online (Sandbox Code Playgroud)
Ada*_*zia 162
对于有兴趣在每个请求的基础上应用此解决方案的任何人,这是一个选项并使用Lambda表达式.同样的Lambda表达式也可以应用于blak3r提到的全局过滤器.此方法似乎需要.NET 4.5.
String url = "https://www.stackoverflow.com";
HttpWebRequest request = HttpWebRequest.CreateHttp(url);
request.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
Run Code Online (Sandbox Code Playgroud)
在.NET 4.0中,Lambda表达式可以应用于全局过滤器
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
Run Code Online (Sandbox Code Playgroud)
San*_*nen 66
由于只有一个全局ServicePointManager,因此设置ServicePointManager.ServerCertificateValidationCallback将产生所有后续请求将继承此策略的结果.由于它是一个全局"设置",因此最好在Global.asax的Application_Start方法中设置它.
设置回调会覆盖默认行为,您可以自己创建自定义验证例程.
bla*_*k3r 51
这对我有用:
System.Net.ServicePointManager.ServerCertificateValidationCallback +=
delegate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate,
System.Security.Cryptography.X509Certificates.X509Chain chain,
System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
return true; // **** Always accept
};
Run Code Online (Sandbox Code Playgroud)
来自这里的代码片段:http://www.west-wind.com/weblog/posts/2011/Feb/11/HttpWebRequest-and-Ignoring-SSL-Certificate-Errors
And*_*mel 23
还有一个简短的委托解决方案:
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
Run Code Online (Sandbox Code Playgroud)
顺便说一句,这是我所知道的在给定应用程序中关闭所有证书验证的最简单的方法:
ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => true;
Run Code Online (Sandbox Code Playgroud)
小智 6
对于 .net 核心
using (var handler = new HttpClientHandler())
{
// allow the bad certificate
handler.ServerCertificateCustomValidationCallback = (request, cert, chain, errors) => true;
using (var httpClient = new HttpClient(handler))
{
await httpClient.PostAsync("the_url", null);
}
}
Run Code Online (Sandbox Code Playgroud)
有人提到在.NET 4.5之前,访问它的请求的属性ServicePointManager不可用.
这是.NET 4.0代码,它允许您ServicePoint基于每个请求访问.它不允许您访问每个请求的回调,但它应该让您找到有关该问题的更多详细信息.只需访问scvPoint.Certificate(或者ClientCertificate如果您愿意)属性.
WebRequest request = WebRequest.Create(uri);
// oddity: these two .Address values are not necessarily the same!
// The service point appears to be related to the .Host, not the Uri itself.
// So, check the .Host vlaues before fussing in the debugger.
//
ServicePoint svcPoint = ServicePointManager.FindServicePoint(uri);
if (null != svcPoint)
{
if (!request.RequestUri.Host.Equals(svcPoint.Address.Host, StringComparison.OrdinalIgnoreCase))
{
Debug.WriteLine(".Address == " + request.RequestUri.ToString());
Debug.WriteLine(".ServicePoint.Address == " + svcPoint.Address.ToString());
}
Debug.WriteLine(".IssuerName == " + svcPoint.Certificate.GetIssuerName());
}
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以在 HttpClient 的本地实例上设置回调,而不是向 ServicePointManager 添加回调,这将覆盖全局证书验证。此方法应仅影响使用该 HttpClient 实例进行的调用。
以下示例代码显示了如何在 Web API 控制器中实现忽略特定服务器的证书验证错误。
using System.Net.Http;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
public class MyController : ApiController
{
// use this HttpClient instance when making calls that need cert errors suppressed
private static readonly HttpClient httpClient;
static MyController()
{
// create a separate handler for use in this controller
var handler = new HttpClientHandler();
// add a custom certificate validation callback to the handler
handler.ServerCertificateCustomValidationCallback = ((sender, cert, chain, errors) => ValidateCert(sender, cert, chain, errors));
// create an HttpClient that will use the handler
httpClient = new HttpClient(handler);
}
protected static ValidateCert(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors)
{
// set a list of servers for which cert validation errors will be ignored
var overrideCerts = new string[]
{
"myproblemserver",
"someotherserver",
"localhost"
};
// if the server is in the override list, then ignore any validation errors
var serverName = cert.Subject.ToLower();
if (overrideCerts.Any(overrideName => serverName.Contains(overrideName))) return true;
// otherwise use the standard validation results
return errors == SslPolicyErrors.None;
}
}
Run Code Online (Sandbox Code Playgroud)
CA5386:漏洞分析工具会提醒您注意这些代码。
正确代码:
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) =>
{
return (sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) != SslPolicyErrors.RemoteCertificateNotAvailable;
};
Run Code Online (Sandbox Code Playgroud)