Inheritance: X509Certificate
Example #1
1
        protected Saml2Request UnbindInternal(HttpRequestBase request, Saml2Request saml2RequestResponse, X509Certificate2 signatureValidationCertificate)
        {
            if (request == null)
                throw new ArgumentNullException("request");

            if (saml2RequestResponse == null)
                throw new ArgumentNullException("saml2RequestResponse");

            if (signatureValidationCertificate == null)
            {
                throw new ArgumentNullException("signatureValidationCertificate");
            }
            if (signatureValidationCertificate.PublicKey == null)
            {
                throw new ArgumentException("No Public Key present in Signature Validation Certificate.");
            }
            if (!(signatureValidationCertificate.PublicKey.Key is DSA || signatureValidationCertificate.PublicKey.Key is RSACryptoServiceProvider))
            {
                throw new ArgumentException("The Public Key present in Signature Validation Certificate must be either DSA or RSACryptoServiceProvider.");
            }

            saml2RequestResponse.SignatureValidationCertificate = signatureValidationCertificate;

            return saml2RequestResponse;
        }
        public Client(String host, Int32 port)
        {
            try
            {

                clientName = Dns.GetHostName();

            }
            catch (SocketException se)
            {

                MessageBox.Show("ERROR: Could not retrieve client's DNS hostname.  Please try again." + se.Message + ".", "Client Socket Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;

            }

            serverName = host;
            gamePort = port;
            client = new TcpClient(host, port);
            netStream = client.GetStream();
            reader = new StreamReader(netStream);
            writer = new StreamWriter(netStream);
            ssl = new SslStream(netStream, false, new RemoteCertificateValidationCallback(ValidateCert));
            cert = new X509Certificate2("server.crt");
            ssl.AuthenticateAsClient(serverName);
            writer.AutoFlush = true;
        }
        private bool LoadCertificateByThumbprint(string thumbprint)
        {
            thumbprint = thumbprint.Replace(" ", "").ToUpperInvariant();
            StoreName storeName = StoreName.My;
            StoreLocation storeLocation = StoreLocation.LocalMachine;
            X509Store store = new X509Store(storeName, storeLocation);

            try
            {
                store.Open(OpenFlags.ReadOnly);

                foreach (var cert in store.Certificates)
                {
                    if (cert.HasPrivateKey == false)
                        continue;

                    if (String.Compare(cert.Thumbprint, thumbprint) == 0)
                    {
                        _certificate = cert;
                        break;
                    }
                }
            }
            finally
            {
                store.Close();
            }

            if (_certificate == null)
            {
                throw new InvalidOperationException("The certificate with the thumbprint " + thumbprint + " could not be found.");
            }

            return true;
        }
Example #4
0
		// constructors

		// only accessible from X509Chain.ChainElements
		internal X509ChainElement (X509Certificate2 certificate)
		{
			this.certificate = certificate;
			// so far String.Empty is the only thing I've seen. 
			// The interesting stuff is inside X509ChainStatus.Information
			info = String.Empty;
		}
        private JsonWebSecurityTokenHandler GetSecurityTokenHandler(string audience,
            string authMetadataEndpoint,
            X509Certificate2 currentCertificate)
        {
            JsonWebSecurityTokenHandler jsonTokenHandler = new JsonWebSecurityTokenHandler();
            jsonTokenHandler.Configuration = new Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration();

            jsonTokenHandler.Configuration.AudienceRestriction = new Microsoft.IdentityModel.Tokens.AudienceRestriction(AudienceUriMode.Always);
            jsonTokenHandler.Configuration.AudienceRestriction.AllowedAudienceUris.Add(
              new Uri(audience, UriKind.RelativeOrAbsolute));

            jsonTokenHandler.Configuration.CertificateValidator = X509CertificateValidator.None;

            jsonTokenHandler.Configuration.IssuerTokenResolver =
              SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
                new ReadOnlyCollection<SecurityToken>(new List<SecurityToken>(
                  new SecurityToken[]
            {
              new X509SecurityToken(currentCertificate)
            })), false);

            Microsoft.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry issuerNameRegistry =
                new Microsoft.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry();
            issuerNameRegistry.AddTrustedIssuer(currentCertificate.Thumbprint, Config.ExchangeApplicationIdentifier);
            jsonTokenHandler.Configuration.IssuerNameRegistry = issuerNameRegistry;

            return jsonTokenHandler;
        }
        public string assinarEmLote(string xml, X509Certificate2 certificado)
        {

            XmlDocument doc = new XmlDocument();
            doc.PreserveWhitespace = false;
            doc.LoadXml(xml);

            XmlNodeList atributos = doc.ChildNodes.Item(0).ChildNodes;

            for ( int count = 0; count < atributos.Count; count++ )
            {
                if (!atributos.Item(count).Name.Equals("RPS"))
                    continue;

                XmlNode rpsNode = atributos.Item(count);

                string referencia = DefinirReferenciaParaAssinaturaRPS(rpsNode);

                string referenciaCriptografada = CriptografarReferencia(referencia, certificado);

                rpsNode.ChildNodes.Item(0).InnerText = referenciaCriptografada;
            }
            
            return doc.OuterXml;
        }
 public SignatureProcessor(X509Certificate2 certificate, ProtocolSettings discoveryInfo)
 {
     this.Certificate = certificate;
     this.discoveryInfo = discoveryInfo;
     this.SHA1SignatureName = ProtocolStrings.SignatureAlgorithmSHA1Uri;
     this.references = new List<ReferenceEntry>();
 }
        /// <summary>
        /// Encrypts the DecryptedPassword using the EncryptionAlgorithm and places the result in Password
        /// </summary>
        public override void Encrypt(X509Certificate2 certificate, byte[] senderNonce, string securityPolicyUri)
        {
            if (m_decryptedPassword == null)
            {
                m_password = null;
                return;
            }

            // handle no encryption.
            if (String.IsNullOrEmpty(securityPolicyUri) || securityPolicyUri == SecurityPolicies.None)
            {
                m_password = new UTF8Encoding().GetBytes(m_decryptedPassword);
                m_encryptionAlgorithm = null;
                return;
            }
            
            // encrypt the password.
            byte[] dataToEncrypt = Utils.Append(new UTF8Encoding().GetBytes(m_decryptedPassword), senderNonce);

            EncryptedData encryptedData = SecurityPolicies.Encrypt(
                certificate,
                securityPolicyUri,
                dataToEncrypt);
                        
            m_password = encryptedData.Data;
            m_encryptionAlgorithm = encryptedData.Algorithm; 
        }
        public void Decrypt(XmlDocument document, X509Certificate2 encryptionCert)
        {
            var assertion = document.FindChild(EncryptedAssertion);
            if (assertion == null) return; // Not encrypted, shame on them.

            var data = document.EncryptedChild("EncryptedData");
            var keyElement = assertion.EncryptedChild("EncryptedKey");

            var encryptedData = new EncryptedData();
            encryptedData.LoadXml(data);

            var encryptedKey = new EncryptedKey();
            encryptedKey.LoadXml(keyElement);

            var encryptedXml = new EncryptedXml(document);

            // Get encryption secret key used by decrypting with the encryption certificate's private key
            var secretKey = GetSecretKey(encryptedKey, encryptionCert.PrivateKey);

            // Seed the decryption algorithm with secret key and then decrypt
            var algorithm = GetSymmetricBlockEncryptionAlgorithm(encryptedData.EncryptionMethod.KeyAlgorithm);
            algorithm.Key = secretKey;
            var decryptedBytes = encryptedXml.DecryptData(encryptedData, algorithm);

            // Put decrypted xml elements back into the document in place of the encrypted data
            encryptedXml.ReplaceData(assertion, decryptedBytes);
        }
 public AzureCurrentDeployment(string deploymentPrivateId, string subscriptionId, X509Certificate2 certificate, IProvisioningObserver observer = null)
 {
     _subscriptionId = subscriptionId;
     _certificate = certificate;
     _deploymentPrivateId = deploymentPrivateId;
     _observer = observer;
 }
Example #11
0
        /// <summary>
        /// Create a service connection to google.
        /// </summary>
        /// <param name="userEmail">The API email to use for authentication.</param>
        /// <param name="gService">The type of service to connect to.</param>
        /// <returns>Returns an open connection to the google api service, or null.</returns>
        private static BaseClientService BuildService(string userEmail, GoogleServices gService = GoogleServices.Directory)
        {
            X509Certificate2 certificate = new X509Certificate2(Properties.Resources.gsd_api,"notasecret", X509KeyStorageFlags.Exportable);

            ServiceAccountCredential credential = new ServiceAccountCredential(
                new ServiceAccountCredential.Initializer(SERVICE_ACCOUNT_EMAIL)
                {
                    Scopes = Scopes,
                    User = userEmail
                }.FromCertificate(certificate));

            switch (gService)
            {
                case GoogleServices.Directory:
                    DirectoryService directoryService = new DirectoryService(new BaseClientService.Initializer()
                        {
                            HttpClientInitializer = credential,
                            ApplicationName = "GSD GAMS",
                        });
                    return directoryService;
                case GoogleServices.Drive:
                    DriveService driveService = new DriveService(new BaseClientService.Initializer()
                        {
                            HttpClientInitializer = credential,
                            ApplicationName = "GSD GAMS",
                        });
                    return driveService;
            }
            return null;
        }
Example #12
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            var cert = new X509Certificate2(Path.Combine(_environment.ApplicationBasePath, "idsrv4test.pfx"), "idsrv3test");
            var builder = services.AddIdentityServer(options =>
        {
                options.SigningCertificate = cert;
            });
            
            builder.AddInMemoryClients(Clients.Get());
            builder.AddInMemoryScopes(Scopes.Get());
            builder.AddInMemoryUsers(Users.Get());

            builder.AddCustomGrantValidator<CustomGrantValidator>();


            // for the UI
            services
                .AddMvc()
                .AddRazorOptions(razor =>
                {
                    razor.ViewLocationExpanders.Add(new CustomViewLocationExpander());
                });
            services.AddTransient<UI.Login.LoginService>();
            services.AddTransient<UI.SignUp.SignUpService>();
            services.AddTransient<ISmsSender, MessageServices>();
            services.Configure<ASPmsSercetCredentials>(Configuration);



        }
Example #13
0
 /// <summary>
 /// Method to submit the request to create new storage account and return request token.
 /// </summary>
 /// <param name="subscriptionId">Subscription id</param>
 /// <param name="cert">Auth certificate</param>
 /// <param name="input">Input required to create new storage acc</param>
 /// <returns>Token to track the progress of storage account creation</returns>
 public static string CreateStorageAcc(string subscriptionId, CreateStorageServiceInput input, X509Certificate2 cert)
 {
     ClientOutputMessageInspector messageInspector;
     IServiceManagement serviceManager = ServiceInitializer.Get(cert, out messageInspector);
     serviceManager.CreateStorageAccount(subscriptionId, input);
     return messageInspector.ResponseMessage.Headers["x-ms-request-id"];
 }
 public AzureDiscovery(string subscriptionId, X509Certificate2 certificate, IProvisioningObserver observer = null)
 {
     _subscriptionId = subscriptionId;
     _certificate = certificate;
     _observer = observer;
     _policies = new RetryPolicies(observer);
 }
        public int Add(X509Certificate2 certificate)
        {
            if (certificate == null)
                throw new ArgumentNullException("certificate");

            return List.Add(certificate);
        }
    public DeploymentServerCertificateValidator(X509Certificate2 allowedCertificate) {
      if (allowedCertificate == null) {
        throw new ArgumentNullException("allowedCertificate");
      }

      this.allowedCertificate = allowedCertificate;
    }
        private static IAppBuilder ConfigureMiddleware(this IAppBuilder app, string issuerName, X509Certificate2 signingCertificate, string authenticationType)
        {
            if (string.IsNullOrWhiteSpace(issuerName)) throw new ArgumentNullException("issuerName");
            if (signingCertificate == null) throw new ArgumentNullException("signingCertificate");

            var audience = issuerName;

            if (!audience.EndsWith("/"))
            {
                audience += "/";
            }

            audience += "resources";

            app.UseJwtBearerAuthentication(new Microsoft.Owin.Security.Jwt.JwtBearerAuthenticationOptions
            {
                AuthenticationType = authenticationType,

                AllowedAudiences = new[] { audience },
                IssuerSecurityTokenProviders = new[] 
                        {
                            new X509CertificateSecurityTokenProvider(
                                issuerName,
                                signingCertificate)
                        }
            });

            return app;
        }
 private static void ValidateCertificate(X509Certificate2 certificate)
 {
     if (certificate == null)
     {
         throw new ArgumentException("Certificate is required", nameof(certificate));
     }
     if (!certificate.HasPrivateKey)
     {
         throw new ArgumentException("Certificate has no private key and cannot be used for token signing", nameof(certificate));
     }
     try
     {
         // ReSharper disable once UnusedVariable
         var pk = certificate.PrivateKey;
     }
     catch (Exception e)
     {
         throw new ArgumentException(
             "Certificate has a private key, but it cannot be accessed. " +
             "Either user account has no permission to access private key or this is a CNG certificate. " +
             "Only CSP certificates are fully supported by X509Certificate2.",
             nameof(certificate),
             e);
     }
 }
        private static string GetSubjectKeyIdentifier(X509Certificate2 certificate)
        {
            const string SubjectKeyIdentifierOid = "2.5.29.14";
            var extension = certificate.Extensions[SubjectKeyIdentifierOid] as X509SubjectKeyIdentifierExtension;

            return extension == null ? null : extension.SubjectKeyIdentifier;
        }
        /// <summary>
        /// Create Saml2 based Metadata
        /// </summary>
        /// <returns></returns>
        public EntityDescriptor CreateMetadata()
        {
            _entityId = ConfigurationRepository.Global.IssuerUri;

            _signingCertificate = ConfigurationRepository.Keys.SigningCertificate;

            var descriptor = new EntityDescriptor(new Microsoft.IdentityModel.Protocols.WSFederation.Metadata.EntityId(_entityId));

            var role = new ServiceProviderSingleSignOnDescriptor() { WantAssertionsSigned = true, AuthenticationRequestsSigned = true };

            if (_signingCertificate != null)
            {
                Microsoft.IdentityModel.Protocols.WSFederation.Metadata.KeyDescriptor keyDescriptor = CreateKeyDescriptor(_signingCertificate);
                keyDescriptor.Use = Microsoft.IdentityModel.Protocols.WSFederation.Metadata.KeyType.Signing;
                role.Keys.Add(keyDescriptor);
            }

            role.ProtocolsSupported.Add(new Uri("urn:oasis:names:tc:SAML:2.0:protocol"));

            role.AssertionConsumerService.Add(0, new IndexedProtocolEndpoint(0, ProtocolBindings.HttpPost, new Uri(_endpoints.Saml2ASTPost.AbsoluteUri)) { IsDefault = true });
            role.SingleLogoutServices.Add(new ProtocolEndpoint(ProtocolBindings.HttpPost, new Uri(_endpoints.Saml2SLOPOST.AbsoluteUri)) { ResponseLocation = new Uri(_endpoints.Saml2SLOPostResponse.AbsoluteUri) });

            //
            // Artifact binding and single logout is only supported if there is a signing cerificate.
            //
            if (_signingCertificate != null)
            {
                role.AssertionConsumerService.Add(1, new IndexedProtocolEndpoint(1, ProtocolBindings.HttpArtifact, new Uri(_endpoints.Saml2ASTArtifact.AbsoluteUri)));
                role.AssertionConsumerService.Add(2, new IndexedProtocolEndpoint(2, ProtocolBindings.HttpRedirect, new Uri(_endpoints.Saml2ASTRedirect.AbsoluteUri)));
                role.SingleLogoutServices.Add(new ProtocolEndpoint(ProtocolBindings.HttpRedirect, new Uri(_endpoints.Saml2SLORedirect.AbsoluteUri)) { ResponseLocation = new Uri(_endpoints.Saml2SLORedirectResponse.AbsoluteUri) });
            }

            descriptor.RoleDescriptors.Add(role);
            return descriptor;
        }
 public static IGatewayServiceManagement CreateGatewayManagementChannel(Binding binding, Uri remoteUri, X509Certificate2 cert)
 {
     WebChannelFactory<IGatewayServiceManagement> factory = new WebChannelFactory<IGatewayServiceManagement>(binding, remoteUri);
     factory.Endpoint.Behaviors.Add(new ServiceManagementClientOutputMessageInspector());
     factory.Credentials.ClientCertificate.Certificate = cert;
     return factory.CreateChannel();
 }
Example #22
0
        public static void AddCrlForCertificate(
            X509Certificate2 cert,
            SafeX509StoreHandle store,
            X509RevocationMode revocationMode,
            DateTime verificationTime,
            ref TimeSpan remainingDownloadTime)
        {
            // In Offline mode, accept any cached CRL we have.
            // "CRL is Expired" is a better match for Offline than "Could not find CRL"
            if (revocationMode != X509RevocationMode.Online)
            {
                verificationTime = DateTime.MinValue;
            }

            if (AddCachedCrl(cert, store, verificationTime))
            {
                return;
            }

            // Don't do any work if we're over limit or prohibited from fetching new CRLs
            if (remainingDownloadTime <= TimeSpan.Zero ||
                revocationMode != X509RevocationMode.Online)
            {
                return;
            }

            DownloadAndAddCrl(cert, store, ref remainingDownloadTime);
        }
        internal X509CertificateEndpointIdentity(XmlDictionaryReader reader)
        {
            if (reader == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");

            reader.MoveToContent();
            if (reader.IsEmptyElement)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.Format(SR.UnexpectedEmptyElementExpectingClaim, XD.AddressingDictionary.X509v3Certificate.Value, XD.AddressingDictionary.IdentityExtensionNamespace.Value)));

            reader.ReadStartElement(XD.XmlSignatureDictionary.X509Data, XD.XmlSignatureDictionary.Namespace);
            while (reader.IsStartElement(XD.XmlSignatureDictionary.X509Certificate, XD.XmlSignatureDictionary.Namespace))
            {
                reader.MoveToContent();
                X509Certificate2 certificate = new X509Certificate2(Convert.FromBase64String(reader.ReadContentAsString()));
                if (certificateCollection.Count == 0)
                {
                    // This is the first certificate. We assume this as the primary 
                    // certificate and initialize the base class.
                    Initialize(new Claim(ClaimTypes.Thumbprint, certificate.GetCertHash(), Rights.PossessProperty));
                }

                certificateCollection.Add(certificate);
            }

            reader.ReadEndElement();

            if (certificateCollection.Count == 0)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.Format(SR.UnexpectedEmptyElementExpectingClaim, XD.AddressingDictionary.X509v3Certificate.Value, XD.AddressingDictionary.IdentityExtensionNamespace.Value)));
        }
        internal AzureHDInsightSubscriptionResolverSimulator()
        {
            var certificate = new X509Certificate2(Convert.FromBase64String(IntegrationTestBase.TestCredentials.Certificate), string.Empty);
            AzureSession.DataStore.AddCertificate(certificate);
            ProfileClient profileClient = new ProfileClient(new AzureSMProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile)));
            profileClient.Profile.Accounts[certificate.Thumbprint] = new AzureAccount
            {
                Id = certificate.Thumbprint,
                Type = AzureAccount.AccountType.Certificate,
                Properties =
                    new Dictionary<AzureAccount.Property, string>
                    {
                        {
                            AzureAccount.Property.Subscriptions,
                            IntegrationTestBase.TestCredentials.SubscriptionId.ToString()
                        }
                    }
            };
            profileClient.Profile.Save();

            this.knownSubscriptions = new AzureSubscription[]
                {
                    new AzureSubscription()
                        {
                            Id = IntegrationTestBase.TestCredentials.SubscriptionId,
                            Account = certificate.Thumbprint,
                            Environment = EnvironmentName.AzureCloud
                        }, 
                };
        }
Example #25
0
        public SslServer(X509Certificate2 cert, bool certRequired, SslProtocols enabledProt, bool expectedExcep)
        {
            certificate = cert;
            clientCertificateRequired = certRequired;
            enabledSslProtocols = enabledProt;
            expectedException = expectedExcep;

            if (!certificate.HasPrivateKey)
            {
                Console.WriteLine("ERROR: The cerfiticate does not have a private key.");
                throw new Exception("No Private Key in the certificate file");
            }

            //Get the IPV4 address on this machine which is all that the MF devices support.
            foreach (IPAddress address in Dns.GetHostAddresses(Dns.GetHostName()))
            {
                if (address.AddressFamily == AddressFamily.InterNetwork)
                {
                    ipAddress = address;
                    break;
                }
            }

            if (ipAddress == null)
                throw new Exception("No IPV4 address found.");

            //Console.WriteLine("ipAddress is: " + ipAddress.ToString());
            //Console.WriteLine("port          is: " + port.ToString());
        }
        public Certificate(X509Certificate2 cert)
        {
            if (cert == null)
            {
                throw new ArgumentNullException("cert");
            }

            certificate = cert;

            KeyAlgorithm = certificate.GetKeyAlgorithm();
            HasPrivateKey = certificate.HasPrivateKey;
            SerialNumber = certificate.SerialNumber;
            Thumbprint = certificate.Thumbprint;
            FriendlyName = certificate.FriendlyName;// !string.IsNullOrWhiteSpace(_certificate.FriendlyName) ? _certificate.FriendlyName : string.Format("[{0}]\t[{1}]", _certificate.Issuer, _certificate.Subject);
            Subject = certificate.Subject;
            EffectiveDate = certificate.NotBefore;
            ExpirationDate = certificate.NotAfter;
            Format = certificate.GetFormat();
            Issuer = certificate.Issuer;
            SignatureAlgorithm = certificate.SignatureAlgorithm.FriendlyName;
            Version = certificate.Version.ToString();

            Extentions = new List<string>();
            foreach (X509Extension ext in certificate.Extensions)
            {
                Extentions.Add(ext.Format(false));
            }
        }
        public void CreateWebRequest_returns_request_with_xml_contenttype()
        {
            var certificate = new X509Certificate2();

            var request = ServiceManagementRequest.CreateWebRequest(new Uri("http://foo.bar.baz"), certificate);
            Assert.AreEqual("application/xml", request.ContentType);
        }
Example #28
0
        public static ActionResult InstallCert(Session session)
        {
            var cert = RSA.GetCACertificate();
            if (cert != null) return ActionResult.Success;

            var tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

            Configuration.ServerAddress = Configuration.ServerAddress.Replace("https://", "http://");
            var keyPath = string.Format("{0}ca.cert.der", tempDirectory);
            var downloaded = Communication.DownloadFile("/management/other/ca.cert.der", keyPath);
            if (!downloaded)
            {
                DisplayMSIError(session, "Failed to download CA certificate");
                return ActionResult.Failure;
            }

            try
            {
                cert = new X509Certificate2(keyPath);
                var store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadWrite);
                store.Add(cert);

                store.Close();
                return ActionResult.Success;
            }
            catch (Exception ex)
            {
                DisplayMSIError(session, "Unable to install CA certificate: " + ex.Message);
                return ActionResult.Failure;
            }
        }
        public Task AuthenticateAsClient(X509Certificate2 certificate)
        {
            var ssl = new SslStream(Stream, false, (sender, x509Certificate, chain, errors) =>
            {
                if (errors.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch))
                {
                    return true;
                }

                // if (errors == SslPolicyErrors.None)
                //return true;
                return true;
            }, null);

            var tempStream = new SslStreamWrapper(ssl);
            Stream = tempStream;

            Func<AsyncCallback, object, IAsyncResult> begin =
                (cb, s) => ssl.BeginAuthenticateAsClient(this.RemoteIpAddress,
                    new X509Certificate2Collection(certificate),SslProtocols.Tls, false, cb, s);

            var task = Task.Factory.FromAsync(begin, ssl.EndAuthenticateAsClient, null);
           
            return task;
        }
        public async Task GetServiceInfo()
        {
            var clientCertificate = new X509Certificate2(@"Certs\testwebapplication.pfx", "password");
            this.appConfig.ActiveDirectoryClientCertificate = clientCertificate;
            this.appConfig.ActiveDirectoryServiceEndpointUrl = "https://service/";

            var serviceInfo = await this.serviceInfoProvider.GetServiceInfo(
                this.appConfig,
                this.credentialCache.Object,
                this.httpProvider.Object,
                ClientType.Business) as AdalServiceInfo;

            Assert.IsNotNull(serviceInfo, "Unexpected service info type.");

            var authenticationProvider = serviceInfo.AuthenticationProvider as AdalAuthenticationProvider;
            Assert.IsNotNull(authenticationProvider, "Unexpected authentication provider type.");

            Assert.AreEqual(serviceInfo, authenticationProvider.ServiceInfo, "Unexpected service info set on authentication provider.");

            Assert.AreEqual(this.appConfig.ActiveDirectoryAppId, serviceInfo.AppId, "Unexpected app ID set.");
            Assert.AreEqual(this.credentialCache.Object, serviceInfo.CredentialCache, "Unexpected credential cache set.");
            Assert.AreEqual(this.httpProvider.Object, serviceInfo.HttpProvider, "Unexpected HTTP provider set.");
            Assert.AreEqual(this.appConfig.ActiveDirectoryClientSecret, serviceInfo.ClientSecret, "Unexpected client secret set.");
            Assert.AreEqual(this.appConfig.ActiveDirectoryReturnUrl, serviceInfo.ReturnUrl, "Unexpected return URL set.");
            Assert.AreEqual(clientCertificate, serviceInfo.ClientCertificate, "Unexpected certificate set.");
            Assert.AreEqual(this.serviceInfoProvider.UserSignInName, serviceInfo.UserId, "Unexpected user ID set.");
            Assert.AreEqual(this.appConfig.ActiveDirectoryServiceEndpointUrl, serviceInfo.BaseUrl, "Unexpected base URL set.");
            Assert.IsNull(serviceInfo.WebAuthenticationUi, "Unexpected web UI set.");
        }