Created
February 9, 2020 08:23
-
-
Save zahedshareef/d9956e5e2769e497081493b3a08ba19e to your computer and use it in GitHub Desktop.
Check for Certificate Expiration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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