简体   繁体   中英

Get list of X509Certificate from cert store C# MVC

I'm trying to get the list of certificates from cert store. This is the code I'm using from this post Get list of certificates from the certificate store in C# :

X509Store store = new X509Store(StoreName.My);
store.Open(OpenFlags.ReadOnly);
foreach (X509Certificate2 mCert in store.Certificates)
{
  // TODO
}

When I run this code from Test Explorer is finding all available certificates, but when I run it on my MVC application is not returning any certificate. I'm running VS 2013 as administrator.

Could you please address me what I'm doing wrong?

EDIT:

When I'm running the code on IIS Express I'm getting the list of certificates, but when I run it on Local IIS I'm not getting any results.

Regards,

Most of the time, you want to check the machine store certs, not the ones for your current user. To do that:

X509Store store = new X509Store(StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
foreach (X509Certificate2 certificate in store.Certificates)
{
    // TODO
}

This gives you a consistent list, regardless of the IIS user.

If you're attempting to accept certificates from a user, IIS needs to be correctly configured to use HTTPS and accept SSL from the client. You won't be able to go from IIS Express and, let's say, IIS 8.0 without making a few changes in your code.

Check out the top rated answer in How do I get the X509Certificate sent from the client in web service? for the IIS code.

For IIS Express, you can't configure the SSL settings so if you want to pseudo-grab x509 attributes you can do so from the local store. It looks like that's what you're doing right now, which won't work on your local IIS because ApplicationPoolIdentity isn't privileged to access the certificate store.

May be you can try this.

X509Store store = new X509Store(StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
foreach (X509Certificate2 mCert in store.Certificates)
{
    // TODO
}

You can iterate the store location and the certifications that exist on your computer by using the example provided on this link X509Store Class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM