I have uploaded Certificates thorough azure new portal while i am not getting these certificates back here is my code
var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certificates = store.Certificates;
try
{
}
finally
{
store.Close();
}
return certificates;
These are the certificates which I always get
enter image description here
Also i have follow this article https://azure.microsoft.com/en-us/blog/using-certificates-in-azure-websites-applications/
Anybody know the reason why i am not getting all the certificates and why i am getting these certificates ?? please help
instead of geeting all certificates i just received these 4, and in the local enviorment i get all certificates which are install on my machine
From my test, the article in your reply help us to use Certificates in Azure web app. However we only could query the certificates with the following conditions:
1) the certificate has been uploaded to Azure web app
2) setting WEBSITE_LOAD_CERTIFICATES in Azure portal with its value set to the certificate thumbprint
It is different with your test on your local machine because Azure web app run in sandbox. For more information about Azure web app sandbox, please refer to this article.
Well, I'm using this function I had found somewhere and is working fine. If you have uploaded all the certificates properly, can you please try running this piece of code. I know it looks the same but you can't really tell.
private X509Certificate2 GetStoreCertificate(string thumbprint)
{
List<StoreLocation> locations = new List<StoreLocation> { StoreLocation.CurrentUser, StoreLocation.LocalMachine };
foreach (var location in locations)
{
Console.WriteLine("location: " + location.ToString());
X509Store store = new X509Store("My", location);
try
{
Console.WriteLine("Try, store.Open...");
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
Console.WriteLine("store.Opened..." + store.Certificates.Count.ToString());
foreach (X509Certificate2 cert in store.Certificates)
{
Console.WriteLine("X509Certificate2 Thumbprint : " + cert.Thumbprint);
}
foreach (X509Certificate cert in store.Certificates)
{
Console.WriteLine("X509Certificate Thumbprint : " + cert.Issuer);
}
X509Certificate2Collection certificates = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);
Console.WriteLine("Finding certificate.." + certificates.Count.ToString());
if (certificates.Count == 1)
{
Console.WriteLine("Atleast one found!!!");
return certificates[0];
}
}
finally
{
store.Close();
}
}
throw new ArgumentException(string.Format("A Certificate with Thumbprint '{0}' could not be located.", thumbprint));
}
Related
Is there a way to read certificates from .p12 file and use them for an SSL/TLS communication while using SSLStreams?
sslstream.AuthenticateAsClient(SERVERNAME, ReadCertificates(), sslProtocol, sslCertRevocationCheck);
private X509Certificate2Collection ReadCertificates()
{
X509Certificate2Collection collection = null;
X509Certificate2Collection collection2 = null;
try
{
String certStore1 = "C:\\Temp\\Certs\\Client.p12";
X509Certificate2 certificate1 = new X509Certificate2(certStore1, "*****");
//Create a collection and add two of the certificates.
collection = new X509Certificate2Collection();
collection.Import(certStore1,"*****",X509KeyStorageFlags.PersistKeySet);
collection2 = new X509Certificate2Collection();
foreach(X509Certificate2 cert in collection)
{
if(cert.HasPrivateKey)
collection2.Add(cert);
}
}
catch(Exception e)
{
Console.WriteLine(e);
}
Console.WriteLine("Certificate collection:" + collection.Count);
return collection2;
}
The above code fails with the following exception
System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
The code works only if the public key of the server is put into the Windows keystore.
Client.p12 contains both the client's private key and the server's public key.
In .NET6 the above can be achieved using AuthenticateAsClient with SslClientAuthenticationOptions and set RemoteCertificateValidationCallback
One of my certificates have been expired. This makes the following code fail :
X509Store store = new X509Store(settings.CertificateStore, settings.CertificateLocation);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindByThumbprint, settings.Thumbprint, true);
store.Close();
if (certs.Count > 0)
{
LogHandler.Instance.Log(LogLev.Info, $"UseSecureConnection > Location:{settings.CertificateLocation}, Store:{settings.CertificateStore}, Thumbprint:{settings.Thumbprint}");
_serviceHost.Credentials.ServiceCertificate.SetCertificate(settings.CertificateLocation,
settings.CertificateStore, X509FindType.FindByThumbprint, settings.Thumbprint);
}
else
throw new Exception("Could not find certificate with thumbprint " + settings.Thumbprint);
This codes worked great uptil certificate got expired.
How do i fetch it even if its expired?
store.Certificates.Find(X509FindType.FindByThumbprint, settings.Thumbprint, false)
should do it. The last parameter is validOnly.
I am using the below method to get certificate from the x509 store
private X509Certificate GetCert(string certThumbPrint)
{
var certStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
certStore.Open(OpenFlags.ReadOnly);
var certCollection = certStore.Certificates.Find(X509FindType.FindByThumbprint, certThumbPrint.Trim(), false);
certStore.Close();
// Check to see if our certificate was added to the collection. If no, throw an error, if yes, create a certificate using it.
if (0 == certCollection.Count || certCollection.Count == null)
{
throw new ApiException(string.Format("Error: Admin Service Client : No certificate found containing thumbprint {0}",certThumbPrint), ApiLogCategory.Configuration, ErrorCodes.AdminServiceClient);
}
var cert = new X509Certificate(certCollection[0].RawData, string.Empty, X509KeyStorageFlags.MachineKeySet);
return cert;
}
I was getting error so I tried debugging and found that the application is unable to open the X509 store. What can I do in this case.
It looks like a permission related issue.
Is your certificate installed in personal store?
if so, Right click the certificate => All tasks => Manage private key => Add IIS AppPool\AppPoolName and grant it Full control
if you're running app pool under a different account than application pool identity then that that user.
I need to access a certificate from my Azure Function.
I followed the steps outlined in Runtime error loading certificate in Azure Functions but it didn't work out.
private static X509Certificate2 GetCertificate(string thumbprint, TraceWriter log)
{
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
try
{
store.Open(OpenFlags.ReadOnly);
log.Info("Enumerating certificates");
foreach (var cert in store.Certificates) {
log.Info(cert.Subject);
}
var col = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);
if (col == null || col.Count == 0)
{
return null;
}
return col[0];
}
finally
{
store.Close();
}
}
Two certificates where uploaded to the Azure Function and the setting WEBSITE_LOAD_CERTIFICATES was added as well and set to either * or to the thumpbrint of the required certificate, but to no avail.
The GetCertificate method should print a list of all certificates in the store, but the store is empty.
Any clues on how to solve this?
UPDATE:
Client certificates are now supported in the Consumption plan.
Client certificates are not yet supported in our Consumption plan, only in App Service plan. This is tracked by an issue in our repo here. We're working on it - please follow that issue for status. Thanks.
I think I have read every single thing on the internet about this (bold statement I know) but I can't work it out...
I have a very simple webpage that gets the status VMs on Azure, which works fine on my machine. I created a Cert on my local machine with makecert and debug runs fine.
After deploying it to another server on IIS all I get is 403 errors.
Things I tried:
Exporting Cert from my dev machine with private key and importing onto the test server
Creating new Cert with makecert (edit: recreated the cert on the server I want to deploy to) (according to this link from MSN), upload to Azure, update code to search for new thumbprint, redeploy and admire the same error msg..
Both times I changed the app pool identity to a user account that is log-on-able (and reverted)
Tried with cert as both localmachine and current user, with user updated in the app pool
I changed my get cert code to more resemble an answer from a similar question, but finding the cert doesn't appear to be the issue.. if I remove the cert created on the server, I get a different error.
var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
var certificate = store.Certificates.Cast<X509Certificate2>().SingleOrDefault(c => string.Equals(c.Thumbprint, thumbprint, StringComparison.OrdinalIgnoreCase)); // please replace CertificateThumbprint with original Thumbprint
return certificate;
Ref: how to connect to azure (management) rest api via C# in IIS
Code to create HttpClient:
WebRequestHandler handler = new WebRequestHandler();
String CertThumbprint = _certthumbprint;
X509Certificate2 managementCert = FindX509Certificate(CertThumbprint);
if (managementCert != null)
{
handler.ClientCertificates.Add(managementCert);
HttpClient httpClient = new HttpClient(handler);
httpClient.DefaultRequestHeaders.Add("x-ms-version", "2014-05-01");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
return httpClient;
}
Retrieve VMs Code:
String uri = String.Format("https://management.core.windows.net/{0}/services/hostedservices/{1}/deploymentslots/{2}", _subscriptionid, ServiceName, "Production");
XDocument vms = new XDocument();
vms.Add(new XElement("VirtualMachines"));
ApplyNamespace(vms.Root, ns);
try
{
HttpClient http = GetHttpClient();
Stream responseStream = await http.GetStreamAsync(uri);
if (responseStream != null)
{
XDocument xml = XDocument.Load(responseStream);
var roles = xml.Root.Descendants(ns + "RoleInstance");
foreach (XElement r in roles)
{
XElement svcNamee1 = new XElement("ServiceName", ServiceName);
ApplyNamespace(svcNamee1, ns);
r.Add(svcNamee1);
vms.Root.Add(r);
}
}
}
This code is currently about 95% copy and paste from here
The resolution for me in this case was to create a new Publishsettings file via powershell and import that on the server via powershell. Then use the thumbprint from that in code. Making a cert on the server and uploading to Azure still doesn't work for whatever reason...