Skip to content

Instantly share code, notes, and snippets.

@zahedshareef
Created February 9, 2020 08:23
Show Gist options
  • Save zahedshareef/d9956e5e2769e497081493b3a08ba19e to your computer and use it in GitHub Desktop.
Save zahedshareef/d9956e5e2769e497081493b3a08ba19e to your computer and use it in GitHub Desktop.
Check for Certificate Expiration
using System;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using Xunit;
namespace CertCheck
{
public class ProductionServerCertificates
{
[Theory]
public void MustHaveAtLeast30DaysLeftBeforeExpiring(string domain)
{
HttpWebRequest request = WebRequest.CreateHttp($"https://{domain}");
request.ServerCertificateValidationCallback += ServerCertificateValidationCallback;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
}
}
private static bool ServerCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
var expirationDate = DateTime.Parse(certificate.GetExpirationDateString());
if (expirationDate - DateTime.Today < TimeSpan.FromDays(30))
{
throw new Exception("Time to renew the certificate!");
}
if (sslPolicyErrors == SslPolicyErrors.None)
{
return true;
}
else
{
throw new Exception("Cert policy errors: " + sslPolicyErrors.ToString());
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment