ASP.NET MVC 3 - Сертификаты - Ошибка конфигурации - PullRequest
3 голосов
/ 16 ноября 2011

У меня есть приложение ASP.NET MVC 3, которое полагается на пользователя сертификатов. Когда я запускаю приложение, я получаю сообщение об ошибке:

Configuration Error 
Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately. 

Parser Error Message: ID1024: The configuration property value is not valid.
Property name: 'serviceCertificate'
Error: 'ID1001: The certificate does not have an associated private key.
Thumbprint: '[ID]''

Source Error: 


Line 278:
Line 279:  <microsoft.identityModel>
Line 280:    <service>
Line 281:      <audienceUris>
Line 282:        <!--<environment name="DEV">-->

ID на самом деле является отпечатком большого пальца. Что я делаю неправильно? Как это исправить? Я подозреваю, что мой сертификат не настроен должным образом. Тем не менее, я не уверен, если это правда, или как даже проверить. Спасибо!

1 Ответ

3 голосов
/ 29 августа 2012

Мне удалось решить эту проблему, выполнив следующие действия. Надеюсь, это поможет.

        public static System.Security.Cryptography.X509Certificates.StoreName StoreName
        {
            get
            {
                StoreName storeName = StoreName.My;
                if (WebConfigurationManager.AppSettings[SigningStoreName] != null)
                    storeName = (StoreName)Enum.Parse(typeof(StoreName), WebConfigurationManager.AppSettings[SigningStoreName]);

                return storeName;
            }
        }

        public static System.Security.Cryptography.X509Certificates.StoreLocation StoreLocation
        {
            get
            {
                StoreLocation storeLocation = StoreLocation.CurrentUser;
                if (WebConfigurationManager.AppSettings[SigningStoreLocation] != null)
                    storeLocation = (StoreLocation)Enum.Parse(typeof(StoreLocation), WebConfigurationManager.AppSettings[SigningStoreLocation]);

                return storeLocation;
            }
        }

        public static SigningCredentials GetSigningCredentials()
        {
            X509Certificate2 cert = CertificateUtil.GetCertificate(StoreName, StoreLocation, WebConfigurationManager.AppSettings[Common.SigningSubjectNameOrThumbprint]);
            string signatureAlgorithm = "http://www.w3.org/2000/09/xmldsig#rsa-sha1"
                    , digestAlgorithm = "http://www.w3.org/2000/09/xmldsig#sha1";

            RSACryptoServiceProvider rsa = cert.PrivateKey as RSACryptoServiceProvider;
            if (rsa == null) rsa = RSA.Create() as RSACryptoServiceProvider;

            RsaSecurityKey rsaKey = new RsaSecurityKey(rsa);
            RsaKeyIdentifierClause rsaClause = new RsaKeyIdentifierClause(rsa);
            SecurityKeyIdentifier signingSki = new SecurityKeyIdentifier(new SecurityKeyIdentifierClause[] { rsaClause });
            SigningCredentials signingCredentials = new SigningCredentials(rsaKey, signatureAlgorithm, digestAlgorithm, signingSki);

            return signingCredentials;
        }

    public static X509Certificate2 GetCertificate(StoreName name, StoreLocation location, string subjectNameOrThumbprint)
    {
        X509Store store = new X509Store(name, location);
        X509Certificate2Collection certificates = null;
        store.Open(OpenFlags.ReadOnly);

        try
        {
            X509Certificate2 result = null;

            certificates = store.Certificates;

            if (certificates != null && certificates.Count > 0)
            {
                result = (from X509Certificate2 cert in certificates
                          where !string.IsNullOrWhiteSpace(cert.Thumbprint)
                          && cert.Thumbprint.ToLower().Replace(" ", "") == subjectNameOrThumbprint.ToLower().Replace(" ", "")
                          select cert
                        ).FirstOrDefault();

                if (result == null)
                    result = (from X509Certificate2 cert in certificates
                              where cert.SubjectName != null
                              && cert.SubjectName.Name.ToLower().Replace(" ", "") == subjectNameOrThumbprint.ToLower().Replace(" ", "")
                              select cert
                              ).FirstOrDefault();
            }

            string errMsg = string.Format("{0} - {1} in {2}", name.ToString(), subjectNameOrThumbprint, location.ToString());

            if (result == null)
                throw new ApplicationException(string.Format("No certificate was found for {0} ", errMsg));
            else if (result.Verify() == false)
                throw new ApplicationException(string.Format("Unable to verify certificate for {0}", errMsg));

            return result;
        }
        finally
        {
            store.Close();
        }
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...