/// <summary>
        /// Evaluate the set of incoming claims.
        /// </summary>
        /// <param name="evaluationContext">The results of the authorization policies that have been evaluated.</param>
        /// <param name="state">The current state of the authorization evaluation.</param>
        /// <returns>true indicates evaluation of the authorization can continue, false will reject the authorization.</returns>
        public bool Evaluate(EvaluationContext evaluationContext, ref object state)
        {
            // A new principal with its associated claims is created for the first identity to have been evaluated by the transport
            // layer.  This principal will be applied to the thread before the operations are called.
            object property = null;

            if (evaluationContext.Properties.TryGetValue("Identities", out property))
            {
                List <IIdentity> identities = property as List <IIdentity>;
                if (identities != null)
                {
                    foreach (IIdentity iIdentity in identities)
                    {
                        ///HACK - we are only interested custom username
                        if (iIdentity.AuthenticationType != "Kerberos")
                        {
                            ClaimSet        claimSet        = MapClaims(iIdentity);
                            ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(iIdentity, claimSet);
                            evaluationContext.Properties["Principal"] = claimsPrincipal;
                            evaluationContext.AddClaimSet(this, claimSet);
                        }
                    }
                }
            }
            else
            {
                // If there was no identity provided by the transport, then a generic identity with no claims is used.  This user
                // will only be able to access 'Unrestricted' methods of an interface.
                ClaimSet emptyClaims = new DefaultClaimSet(ClaimsAuthorizationPolicy.IssuerClaimSet, new Claim[] { });
                evaluationContext.Properties["Principal"] = new ClaimsPrincipal(new GenericIdentity("Default User"), emptyClaims);
            }

            // There is no need to call the evaluation again, everything here is computed in a single pass.
            return(true);
        }
Exemplo n.º 2
0
        protected override ReadOnlyCollection <IAuthorizationPolicy> ValidateTokenCore(SecurityToken token)
        {
            var x509Token = token as X509SecurityToken;
            var serviceEncryptingCertificateSubjectName = ConfigurationManager.AppSettings.Get("serviceDns").ToString();

            // Logika validace certifikatu

            if (x509Token.Certificate.Subject == credentials.ClientEncryptingCertificate.Subject)
            {
                DefaultClaimSet x509ClaimSet = new DefaultClaimSet(ClaimSet.System,
                                                                   new Claim(ClaimTypes.Dns, serviceEncryptingCertificateSubjectName, Rights.PossessProperty));
                List <IAuthorizationPolicy> policies = new List <IAuthorizationPolicy>(1);
                policies.Add(new MyAuthorizationPolicy(x509ClaimSet));
                return(policies.AsReadOnly());
            }

            if (x509Token.Certificate.Subject == credentials.ServiceSigningCertificate.Subject)
            {
                X509CertificateClaimSet     x509ClaimSet = new X509CertificateClaimSet(x509Token.Certificate);
                List <IAuthorizationPolicy> policies     = new List <IAuthorizationPolicy>(1);
                policies.Add(new MyAuthorizationPolicy(x509ClaimSet));
                return(policies.AsReadOnly());
            }

            if (x509Token.Certificate.Subject == credentials.ClientSigningCertificate.Subject)
            {
                DefaultClaimSet x509ClaimSet = new DefaultClaimSet(ClaimSet.System,
                                                                   new Claim(ClaimTypes.Name, serviceEncryptingCertificateSubjectName, Rights.PossessProperty));
                List <IAuthorizationPolicy> policies = new List <IAuthorizationPolicy>(1);
                policies.Add(new MyAuthorizationPolicy(x509ClaimSet));
                return(policies.AsReadOnly());
            }

            throw new SecurityTokenValidationException();
        }
Exemplo n.º 3
0
        private void CheckClaims(string claimType, string resource)
        {
            IClaimsPrincipal claimsPrincipal = Thread.CurrentPrincipal as IClaimsPrincipal;

            if (claimsPrincipal == null)
            {
                throw new SecurityException("Access is denied. Security principal should be a IClaimsPrincipal type.");
            }

            Claim        issuerName   = Claim.CreateNameClaim(ClaimsAuthorizationPolicy.IssuerName);
            List <Claim> issuerClaims = new List <Claim>();

            issuerClaims.Add(issuerName);

            List <Claim> requiredClaims = new List <Claim>();

            requiredClaims.Add(new Claim(claimType, resource, Rights.PossessProperty));

            DefaultClaimSet claimSet = new DefaultClaimSet(new DefaultClaimSet(issuerClaims), requiredClaims);

            if (!claimsPrincipal.HasRequiredClaims(claimSet))
            {
                throw new SecurityException("Access is denied. Security principal does not satisfy required claims.");
            }
        }
Exemplo n.º 4
0
        protected override ReadOnlyCollection <IAuthorizationPolicy> ValidateTokenCore(SecurityToken token)
        {
            CustomToken CustomToken = token as CustomToken;

            CustomJwtSecurityTokenHandler.CustomJwtSecurityTokenHandler customJwtSecurityTokenHandler = new CustomJwtSecurityTokenHandler.CustomJwtSecurityTokenHandler();

            ReadOnlyCollection <System.Security.Claims.ClaimsIdentity> auth = customJwtSecurityTokenHandler.ValidateToken(token);

            List <System.IdentityModel.Claims.Claim> claimList = new List <System.IdentityModel.Claims.Claim>();

            foreach (System.Security.Claims.ClaimsIdentity claimsIdentity in auth)
            {
                foreach (var claim in claimsIdentity.Claims)
                {
                    claimList.Add(new System.IdentityModel.Claims.Claim(claim.Type, claim.Value, Rights.PossessProperty));
                }
            }

            DefaultClaimSet customClaimSet = new DefaultClaimSet(claimList.ToArray());

            List <IAuthorizationPolicy> policies = new List <IAuthorizationPolicy>(1);

            policies.Add(new CustomTokenAuthorizationPolicy(customClaimSet));

            return(policies.AsReadOnly());
        }
        protected override ReadOnlyCollection <IAuthorizationPolicy> ValidateTokenCore(SecurityToken token)
        {
            KerberosRequestorSecurityToken token2 = (KerberosRequestorSecurityToken)token;
            List <IAuthorizationPolicy>    list   = new List <IAuthorizationPolicy>(1);
            ClaimSet issuance = new DefaultClaimSet(ClaimSet.System, new Claim[] { new Claim(ClaimTypes.Spn, token2.ServicePrincipalName, Rights.PossessProperty) });

            list.Add(new UnconditionalPolicy(System.ServiceModel.Security.SecurityUtils.CreateIdentity(token2.ServicePrincipalName, "Kerberos"), issuance));
            return(list.AsReadOnly());
        }
        protected override ReadOnlyCollection <IAuthorizationPolicy> ValidateTokenCore(SecurityToken token)
        {
            KerberosRequestorSecurityToken kerbToken = (KerberosRequestorSecurityToken)token;
            List <IAuthorizationPolicy>    policies  = new List <IAuthorizationPolicy>(1);
            ClaimSet claimSet = new DefaultClaimSet(ClaimSet.System, new Claim(ClaimTypes.Spn, kerbToken.ServicePrincipalName, Rights.PossessProperty));

            policies.Add(new UnconditionalPolicy(SecurityUtils.CreateIdentity(kerbToken.ServicePrincipalName, SecurityUtils.AuthTypeKerberos), claimSet));
            return(policies.AsReadOnly());
        }
Exemplo n.º 7
0
        /// <summary>
        /// Makes calls to the specified endpoint name in app.config
        /// </summary>
        /// <param name="endpointName">The endpoint to use from app.config</param>
        private static void CallEndpoint(string endpointName)
        {
            Console.WriteLine("\nCalling endpoint {0}\n", endpointName);

            // Create a client with given client endpoint configuration
            CalculatorClient client = new CalculatorClient(endpointName);

            // Create new credentials class
            SamlClientCredentials samlCC = new SamlClientCredentials();

            // Set the client certificate. This is the cert that will be used to sign the SAML token in the symmetric proof key case
            samlCC.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindBySubjectName, "Alice");

            // Set the service certificate. This is the cert that will be used to encrypt the proof key in the symmetric proof key case
            samlCC.ServiceCertificate.SetDefaultCertificate(StoreLocation.CurrentUser, StoreName.TrustedPeople, X509FindType.FindBySubjectName, "localhost");

            // Create some claims to put in the SAML assertion
            IList <Claim> claims = new List <Claim>();

            claims.Add(Claim.CreateNameClaim(samlCC.ClientCertificate.Certificate.Subject));
            ClaimSet claimset = new DefaultClaimSet(claims);

            samlCC.Claims = claimset;

            // set new credentials
            client.ChannelFactory.Endpoint.Behaviors.Remove(typeof(ClientCredentials));
            client.ChannelFactory.Endpoint.Behaviors.Add(samlCC);

            // Call the Add service operation.
            double value1 = 100.00D;
            double value2 = 15.99D;
            double result = client.Add(value1, value2);

            Console.WriteLine("Add({0},{1}) = {2}", value1, value2, result);

            // Call the Subtract service operation.
            value1 = 145.00D;
            value2 = 76.54D;
            result = client.Subtract(value1, value2);
            Console.WriteLine("Subtract({0},{1}) = {2}", value1, value2, result);

            // Call the Multiply service operation.
            value1 = 9.00D;
            value2 = 81.25D;
            result = client.Multiply(value1, value2);
            Console.WriteLine("Multiply({0},{1}) = {2}", value1, value2, result);

            // Call the Divide service operation.
            value1 = 22.00D;
            value2 = 7.00D;
            result = client.Divide(value1, value2);
            Console.WriteLine("Divide({0},{1}) = {2}", value1, value2, result);

            client.Close();
        }
        /// <summary>
        /// Brings buyers and sellers of equities together.
        /// </summary>
        static SettlementDocumentFactory()
        {
            try
            {
                // This is normally created by a channel when it establishes a connection.  But this is a daemon process without a connection, so an
                // authorization policy needs be created explicilty in order to have a thread that can run as an authorized user.
                SettlementDocumentFactory.authorizationPolicy = new AuthorizationPolicy();

                // This queue is filled up with Working Orders that need to be serviced because something changed the matching criteria.
                SettlementDocumentFactory.actionQueue = new WaitQueue <ObjectAction>();

                // This identity and set of claims gives the worker threads access to do anything to the data model.
                List <Claim> listClaims = new List <Claim>();
                listClaims.Add(new Claim(FluidTrade.Core.ClaimTypes.Create, Resources.Application, Rights.PossessProperty));
                listClaims.Add(new Claim(FluidTrade.Core.ClaimTypes.Update, Resources.Application, Rights.PossessProperty));
                listClaims.Add(new Claim(FluidTrade.Core.ClaimTypes.Read, Resources.Application, Rights.PossessProperty));
                listClaims.Add(new Claim(FluidTrade.Core.ClaimTypes.Destroy, Resources.Application, Rights.PossessProperty));
                ClaimSet adminClaims = new DefaultClaimSet(ClaimsAuthorizationPolicy.IssuerClaimSet, listClaims.ToArray());
                SettlementDocumentFactory.claimsPrincipal = new ClaimsPrincipal(
                    new GenericIdentity("*****@*****.**"),
                    adminClaims);

                // This will create an instance of the Mail Merge factory that takes templates and mail merge fields and generates a complete document.  It is
                // loaded up dymanically so that servers that don't have Microsoft Office installed on them will be able to run, but will not be able to
                // generate settlement letters.
                SettlementDocumentFactory.iMailMerge = new MailMerge();

                if (SettlementDocumentFactory.iMailMerge == null)
                {
                    EventLog.Information("This server is unable to process Mail Merge functions.");
                }
                else
                {
                    // These business rules will move negotiation information across the Chinese wall if a counter party exists.
                    DataModel.ConsumerDebtSettlement.ConsumerDebtSettlementRowChanged += OnConsumerDebtSettlementRowChanged;

                    // This thread will execution the actions that are created by changes to the data model.  The triggers themselves can't modify the data
                    // model because the triggers are called from the commit handlers.
                    SettlementDocumentFactory.factoryThread              = new Thread(new ThreadStart(SettlementDocumentFactory.FactoryThread));
                    SettlementDocumentFactory.factoryThread.Name         = "Crossing Thread";
                    SettlementDocumentFactory.factoryThread.IsBackground = true;
                    SettlementDocumentFactory.factoryThread.Start();
                }
            }
            catch (Exception exception)
            {
                if (exception.InnerException != null)
                {
                    EventLog.Error("{0}, {1}", exception.InnerException.Message, exception.InnerException.StackTrace);
                }

                EventLog.Error("{0}, {1}", exception.Message, exception.StackTrace);
            }
        }
Exemplo n.º 9
0
        protected override ReadOnlyCollection <IAuthorizationPolicy> ValidateTokenCore(SecurityToken token)
        {
            RsaSecurityToken rsaToken = (RsaSecurityToken)token;
            List <Claim>     claims   = new List <Claim>(2);

            claims.Add(new Claim(ClaimTypes.Rsa, rsaToken.Rsa, Rights.Identity));
            claims.Add(Claim.CreateRsaClaim(rsaToken.Rsa));

            DefaultClaimSet             claimSet = new DefaultClaimSet(ClaimSet.Anonymous, claims);
            List <IAuthorizationPolicy> policies = new List <IAuthorizationPolicy>(1);

            policies.Add(new UnconditionalPolicy(claimSet, rsaToken.ValidTo));
            return(policies.AsReadOnly());
        }
        protected override ReadOnlyCollection <IAuthorizationPolicy> ValidateTokenCore(SecurityToken token)
        {
            RsaSecurityToken token2 = (RsaSecurityToken)token;
            List <Claim>     claims = new List <Claim>(2)
            {
                new Claim(ClaimTypes.Rsa, token2.Rsa, Rights.Identity),
                Claim.CreateRsaClaim(token2.Rsa)
            };
            DefaultClaimSet issuance = new DefaultClaimSet(ClaimSet.Anonymous, claims);

            return(new List <IAuthorizationPolicy>(1)
            {
                new UnconditionalPolicy(issuance, token2.ValidTo)
            }.AsReadOnly());
        }
Exemplo n.º 11
0
        /// <summary>
        /// Create the permissions needed to access code.
        /// </summary>
        /// <returns>The permission required of a thread before it can execute code.</returns>
        public override IPermission CreatePermission()
        {
            // Unrestricted access allows any Principal to execute the code that follows.
            if (this.Unrestricted)
            {
                return(new ClaimsPrincipalPermission(PermissionState.Unrestricted));
            }

            // This constructs an explicit permission that is needed by the thread's Principal in order for execution to continue.
            // If the thread doesn't posses this set of claims and is not authenticated, then an exception will be thrown.
            ClaimSet claimSet = new DefaultClaimSet(ClaimsAuthorizationPolicy.IssuerClaimSet,
                                                    new Claim(this.ClaimType, this.Resource, Rights.PossessProperty));

            return(new ClaimsPrincipalPermission(this.IsAuthenticated, claimSet));
        }
Exemplo n.º 12
0
        // <snippet1>
        protected override ReadOnlyCollection <IAuthorizationPolicy> ValidateUserNamePasswordCore(string userName, string password)
        {
            if (!ValidateUserNameFormat(userName))
            {
                throw new SecurityTokenValidationException("Incorrect UserName format");
            }

            ClaimSet         claimSet   = new DefaultClaimSet(ClaimSet.System, new Claim(ClaimTypes.Name, userName, Rights.PossessProperty));
            List <IIdentity> identities = new List <IIdentity>(1);

            identities.Add(new GenericIdentity(userName));
            List <IAuthorizationPolicy> policies = new List <IAuthorizationPolicy>(1);

            policies.Add(new UnconditionalPolicy(ClaimSet.System, claimSet, DateTime.MaxValue.ToUniversalTime(), identities));
            return(policies.AsReadOnly());
        }
Exemplo n.º 13
0
        protected override ReadOnlyCollection <IAuthorizationPolicy> ValidateTokenCore(SecurityToken token)
        {
            global::Common.Lib.Common.UsernameToken.UsernameToken usernameToken = token as global::Common.Lib.Common.UsernameToken.UsernameToken;

            // Note that we cannot authenticate the token w/o a password, so it must be retrieved from somewhere
            if (usernameToken.ValidateToken(_passwordProvider.RetrievePassword("User1")) != true)
            {
                throw new SecurityTokenValidationException("Token validation failed");
            }

            // add claims about user here
            DefaultClaimSet UserClaimSet = new DefaultClaimSet(new Claim(ClaimTypes.Name, usernameToken.UsernameInfo.Username, Rights.PossessProperty));

            List <IAuthorizationPolicy> policies = new List <IAuthorizationPolicy>(1);

            policies.Add(new UserNameTokenAuthorizationPolicy(UserClaimSet));
            return(policies.AsReadOnly());
        }
Exemplo n.º 14
0
        ValidateTokenCore(SecurityToken token)
        {
            UserNameSecurityToken userNameToken = token as UserNameSecurityToken;

            // Validate the information contained in the username token. For demonstration
            // purposes, this code just checks that the user name matches the password.
            if (userNameToken.UserName != userNameToken.Password)
            {
                throw new SecurityTokenValidationException("Invalid user name or password");
            }

            // Create just one Claim instance for the username token - the name of the user.
            DefaultClaimSet userNameClaimSet = new DefaultClaimSet(
                ClaimSet.System,
                new Claim(ClaimTypes.Name, userNameToken.UserName, Rights.PossessProperty));
            List <IAuthorizationPolicy> policies = new List <IAuthorizationPolicy>(1);

            policies.Add(new MyAuthorizationPolicy(userNameClaimSet));
            return(policies.AsReadOnly());
        }
Exemplo n.º 15
0
    protected override ReadOnlyCollection <IAuthorizationPolicy> ValidateTokenCore(SecurityToken token)
    {
        var authorizationPolicies = new List <IAuthorizationPolicy>();

        try
        {
            var userNameToken = token as UserNameSecurityToken;
            new CustomUserNameValidator().Validate(userNameToken.UserName, userNameToken.Password);

            var claims = new DefaultClaimSet(ClaimSet.System, new Claim(ClaimTypes.Name, userNameToken.UserName, Rights.PossessProperty));

            authorizationPolicies.Add(new CustomAuthorizationPolicy(claims));
        }
        catch (Exception)
        {
            authorizationPolicies.Add(new InvalidAuthorizationPolicy());
            throw;
        }
        return(authorizationPolicies.AsReadOnly());
    }
Exemplo n.º 16
0
        protected override ReadOnlyCollection <IAuthorizationPolicy> ValidateTokenCore(SecurityToken token)
        {
            CreditCardToken creditCardToken = token as CreditCardToken;

            if (creditCardToken.CardInfo.ExpirationDate < DateTime.UtcNow)
            {
                throw new SecurityTokenValidationException("The credit card has expired");
            }
            if (!IsCardNumberAndExpirationValid(creditCardToken.CardInfo))
            {
                throw new SecurityTokenValidationException("Unknown or invalid credit card");
            }

            // The credit card token has only 1 claim: the card number. The issuer for the claim is the
            // credit card issuer.
            DefaultClaimSet             cardIssuerClaimSet = new DefaultClaimSet(new Claim(ClaimTypes.Name, creditCardToken.CardInfo.CardIssuer, Rights.PossessProperty));
            DefaultClaimSet             cardClaimSet       = new DefaultClaimSet(cardIssuerClaimSet, new Claim(Constants.CreditCardNumberClaim, creditCardToken.CardInfo.CardNumber, Rights.PossessProperty));
            List <IAuthorizationPolicy> policies           = new List <IAuthorizationPolicy>(1);

            policies.Add(new CreditCardTokenAuthorizationPolicy(cardClaimSet));
            return(policies.AsReadOnly());
        }
        public void CheckClaims(IClaimsPrincipal principal)
        {
            IPrincipal p = principal as IPrincipal;

            if (this.m_isAuthenticated && !p.Identity.IsAuthenticated)
            {
                throw new SecurityException("Access is denied. Security principal is not authenticated.");
            }


            if (m_issuer != null)
            {
                Claim c = Claim.CreateNameClaim(m_issuer);
                if (!principal.Issuer.ContainsClaim(c))
                {
                    throw new SecurityException("Access is denied. Invalid claims issuer.");
                }
            }

            if (this.m_requiredClaims.Count == 0)
            {
                return;
            }

            List <Claim> claims = new List <Claim>();

            foreach (string s in this.m_requiredClaims)
            {
                claims.Add(new Claim(s, ClaimsAuthorizationPolicy.Resources.Application, Rights.PossessProperty));
            }

            DefaultClaimSet claimSet = new DefaultClaimSet(claims);

            if (!principal.HasRequiredClaims(claimSet))
            {
                throw new SecurityException("Access is denied. Security principal does not satisfy required claims.");
            }
        }
Exemplo n.º 18
0
        protected override ReadOnlyCollection <IAuthorizationPolicy> ValidateTokenCore(System.IdentityModel.Tokens.SecurityToken token)
        {
            var securityToken = token as SecurityToken;

            if (securityToken != null)
            {
                // Note that we cannot authenticate the token w/o a password, so it must be retrieved from somewhere
                if (securityToken.ValidateToken(_passwordProvider.RetrievePassword("User1")) != true)
                {
                    throw new SecurityTokenValidationException("Token validation failed");
                }

                // Add claims about user here
                var userClaimSet = new DefaultClaimSet(new Claim(ClaimTypes.Name, securityToken.Info.Username, Rights.PossessProperty));

                var policies = new List <IAuthorizationPolicy>(1)
                {
                    new SecurityTokenAuthorizationPolicy(userClaimSet)
                };
                return(policies.AsReadOnly());
            }

            return(null);
        }
        internal SecurityMessageProperty ValidateSecurity(MsmqInputMessage msmqMessage)
        {
            SecurityMessageProperty property        = null;
            X509Certificate2        certificate     = null;
            WindowsSidIdentity      primaryIdentity = null;

            try
            {
                if (MsmqAuthenticationMode.Certificate == base.ReceiveParameters.TransportSecurity.MsmqAuthenticationMode)
                {
                    try
                    {
                        certificate = new X509Certificate2(msmqMessage.SenderCertificate.GetBufferCopy(msmqMessage.SenderCertificateLength.Value));
                        X509SecurityToken token = new X509SecurityToken(certificate, false);
                        ReadOnlyCollection <IAuthorizationPolicy> tokenPolicies = this.x509SecurityTokenAuthenticator.ValidateToken(token);
                        property = new SecurityMessageProperty {
                            TransportToken         = new SecurityTokenSpecification(token, tokenPolicies),
                            ServiceSecurityContext = new ServiceSecurityContext(tokenPolicies)
                        };
                        goto Label_01C4;
                    }
                    catch (SecurityTokenValidationException exception)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(System.ServiceModel.SR.GetString("MsmqBadCertificate"), exception));
                    }
                    catch (CryptographicException exception2)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(System.ServiceModel.SR.GetString("MsmqBadCertificate"), exception2));
                    }
                }
                if (MsmqAuthenticationMode.WindowsDomain == base.ReceiveParameters.TransportSecurity.MsmqAuthenticationMode)
                {
                    byte[] bufferCopy = msmqMessage.SenderId.GetBufferCopy(msmqMessage.SenderIdLength.Value);
                    if (bufferCopy.Length == 0)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(System.ServiceModel.SR.GetString("MsmqNoSid")));
                    }
                    SecurityIdentifier resource = new SecurityIdentifier(bufferCopy, 0);
                    List <Claim>       claims   = new List <Claim>(2)
                    {
                        new Claim(ClaimTypes.Sid, resource, Rights.Identity),
                        Claim.CreateWindowsSidClaim(resource)
                    };
                    ClaimSet issuance = new DefaultClaimSet(ClaimSet.System, claims);
                    List <IAuthorizationPolicy> list2 = new List <IAuthorizationPolicy>(1);
                    primaryIdentity = new WindowsSidIdentity(resource);
                    list2.Add(new UnconditionalPolicy(primaryIdentity, issuance));
                    ReadOnlyCollection <IAuthorizationPolicy> onlys2 = list2.AsReadOnly();
                    property = new SecurityMessageProperty {
                        TransportToken         = new SecurityTokenSpecification(null, onlys2),
                        ServiceSecurityContext = new ServiceSecurityContext(onlys2)
                    };
                }
            }
            catch (Exception exception3)
            {
                if (Fx.IsFatal(exception3))
                {
                    throw;
                }
                if (AuditLevel.Failure == (base.AuditBehavior.MessageAuthenticationAuditLevel & AuditLevel.Failure))
                {
                    this.WriteAuditEvent(AuditLevel.Failure, certificate, primaryIdentity, null);
                }
                throw;
            }
Label_01C4:
            if ((property != null) && (AuditLevel.Success == (base.AuditBehavior.MessageAuthenticationAuditLevel & AuditLevel.Success)))
            {
                this.WriteAuditEvent(AuditLevel.Success, certificate, primaryIdentity, null);
            }
            return(property);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Simulation of price changes in a stock market.
        /// </summary>
        private static void SimulatePrice()
        {
            // This will seed the random number generator.
            Random random = new Random(DateTime.Now.Millisecond);

            // This set of claims gives the current thread the authority to update the price table.
            List <Claim> listClaims = new List <Claim>();

            listClaims.Add(new Claim(Teraque.ClaimTypes.Create, Teraque.Resources.Application, Rights.PossessProperty));
            listClaims.Add(new Claim(Teraque.ClaimTypes.Update, Teraque.Resources.Application, Rights.PossessProperty));
            listClaims.Add(new Claim(Teraque.ClaimTypes.Read, Teraque.Resources.Application, Rights.PossessProperty));
            ClaimSet adminClaims = new DefaultClaimSet(null, listClaims.ToArray());

//			Thread.CurrentPrincipal = new Teraque.ClaimsPrincipal(new GenericIdentity("Price Service"), adminClaims);

            // This thread will run until an external thread sets this property to 'false'.
            while (MarketSimulator.IsPriceSimulatorThreadRunning)
            {
                // The price changes are generated in batches since there is a modest overhead to creating each transaction and applying it to the shared data
                // model.
                using (TransactionScope transactionScope = new TransactionScope())
                {
                    // The middle tier context allows ADO operations to participate in the transaction.
                    DataModel            dataModel            = new DataModel();
                    DataModelTransaction dataModelTransaction = DataModel.CurrentTransaction;

                    // The simulator parameters need to be locked for each batch of simulated price changes.
                    lock (MarketSimulator.syncRoot)
                    {
                        // The prices are not updated continously because it is trying to simulate a communication interface where a batch of prices is updated
                        // periodically.
                        for (int tick = 0; tick < MarketSimulator.batchSize; tick++)
                        {
                            // This will select a random price in the table and change the price by a random amount.
                            int priceIndex = random.Next(MarketSimulator.dataSetMarket.Price.Rows.Count);
                            DataSetMarket.PriceRow priceRow = MarketSimulator.dataSetMarket.Price[priceIndex];

                            // This will simulate a random selection of a price change is quoted. The 'quoteColumn' variable can be used to reference the
                            // selected quote from any price row.  Below, a random row will be selected for the price change.
                            int quoteTypeIndex = random.Next(Enum.GetValues(typeof(QuoteType)).Length);
                            switch ((QuoteType)Enum.GetValues(typeof(QuoteType)).GetValue(quoteTypeIndex))
                            {
                            case QuoteType.Ask:

                                priceRow.AskPrice += Convert.ToDecimal(Math.Round(random.NextDouble() - 0.5, 2));
                                priceRow.AskSize  += Convert.ToDecimal(random.Next(1, 10));
                                break;

                            case QuoteType.Bid:

                                priceRow.BidPrice += Convert.ToDecimal(Math.Round(random.NextDouble() - 0.5, 2));
                                priceRow.BidSize  += Convert.ToDecimal(random.Next(1, 10));
                                break;

                            case QuoteType.Last:

                                priceRow.LastPrice += Convert.ToDecimal(Math.Round(random.NextDouble() - 0.5, 2));
                                priceRow.LastSize  += Convert.ToDecimal(random.Next(1, 10));
                                break;
                            }

                            // This does the work of updating the price table using the external identifiers and the newly generated prices.
                            dataModel.CreatePriceEx(priceRow.AskPrice, priceRow.AskSize, priceRow.BidPrice, priceRow.BidSize, 0.0M, priceRow.ConfigurationId,
                                                    0.0M, priceRow.LastPrice, priceRow.LastSize, 0.0M, 0.0M, 0.0M, new object[] { priceRow.Currency }, new object[] { priceRow.Symbol },
                                                    0.0M, 0.0M);
                        }

                        // This will commit the changes to the price table.
                        transactionScope.Complete();
                    }
                }

                // This allows other threads the chance to run.
                Thread.Sleep(MarketSimulator.interval);
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// Simulation of brokers executing destination orders.
        /// </summary>
        private static void SimulateBroker()
        {
            // This will seed the random number generator.
            Random random = new Random(DateTime.Now.Millisecond);

            // An instance of the data model is required to update it.
            DataModel dataModel = new DataModel();

            // This set of claims gives the current thread the authority to update the price table.
            List <Claim> listClaims = new List <Claim>();

            listClaims.Add(new Claim(Teraque.ClaimTypes.Create, Teraque.Resources.Application, Rights.PossessProperty));
            listClaims.Add(new Claim(Teraque.ClaimTypes.Update, Teraque.Resources.Application, Rights.PossessProperty));
            listClaims.Add(new Claim(Teraque.ClaimTypes.Read, Teraque.Resources.Application, Rights.PossessProperty));
            ClaimSet adminClaims = new DefaultClaimSet(null, listClaims);
//			Thread.CurrentPrincipal = new ClaimsPrincipal(new GenericIdentity("Broker Service"), adminClaims);

            // Every execution requires a user identifier (the user who created the execution) and the broker who executed the
            // trade.  These values are hard coded at the moment but should be more intelligently assigned in the future.
            Guid userId   = Guid.Empty;
            Guid brokerId = Guid.Empty;

            // Operating values are required for the simulation that come from the data model.
            using (TransactionScope transactionScope = new TransactionScope())
            {
                // The middle tier context allows ADO operations to participate in the transaction.
                DataModelTransaction dataModelTransaction = DataModel.CurrentTransaction;

                // The broker for all the executions is hard coded.
                DataModel.EntityRow brokerRow = DataModel.Entity.EntityKeyExternalId0.Find(new object[] { "ZODIAC SECURITIES" });
                brokerRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                dataModelTransaction.AddLock(brokerRow);
                brokerId = brokerRow.EntityId;

                // The user who creates these executions is hard coded.
                DataModel.EntityRow userRow = DataModel.Entity.EntityKeyExternalId0.Find(new object[] { "ADMINISTRATOR" });
                userRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                dataModelTransaction.AddLock(userRow);
                userId = userRow.EntityId;

                // The data model doesn't need to be locked any more.
                transactionScope.Complete();
            }

            // This thread will run until an external thread sets this property to 'false'.
            while (MarketSimulator.IsBrokerSimulatorThreadRunning)
            {
                // Wait for orders to show up in the simulated order book.
                MarketSimulator.orderEvent.WaitOne();

                // The simulator parameters need to be locked for each batch of simulated price changes.
                try
                {
                    Monitor.Enter(MarketSimulator.syncRoot);

                    // This will select a random price in the table and change the price by a random amount.
                    if (MarketSimulator.dataSetMarket.Order.Rows.Count > 0)
                    {
                        // Select a random row from the order book.
                        int orderIndex = random.Next(MarketSimulator.dataSetMarket.Order.Rows.Count);
                        DataSetMarket.OrderRow orderRow = MarketSimulator.dataSetMarket.Order[orderIndex];
                        if (orderRow.IsBusy)
                        {
                            Thread.Sleep(0);
                            continue;
                        }
                        orderRow.IsBusy = true;

                        // This transaction is required to add the new execution.
                        using (TransactionScope transactionScope = new TransactionScope())
                        {
                            // The middle tier context allows ADO operations to participate in the transaction.
                            DataModelTransaction dataModelTransaction = DataModel.CurrentTransaction;

                            // This will simulate a random selection of a price change is quoted. The 'quoteColumn' variable can be
                            // used to reference the selected quote from any price row.  Below, a random row will be selected for
                            // the price change.
                            int actionTypeIndex = random.Next(Enum.GetValues(typeof(ActionType)).Length);
                            switch ((ActionType)Enum.GetValues(typeof(ActionType)).GetValue(actionTypeIndex))
                            {
                            case ActionType.Execute:

                                // This creates a random execution of the remaining shares on the order.
                                DateTime dateTime         = DateTime.Now;
                                Guid     blotterId        = orderRow.BlotterId;
                                Decimal  quantityLeaves   = orderRow.QuantityOrdered - orderRow.QuantityExecuted;
                                Decimal  quantityExecuted = quantityLeaves <= 100 ?
                                                            quantityLeaves :
                                                            Convert.ToDecimal(random.Next(1, Convert.ToInt32(quantityLeaves / 100.0M))) * 100.0M;
                                DataSetMarket.PriceRow priceRow =
                                    MarketSimulator.dataSetMarket.Price.FindByConfigurationIdSymbol("US TICKER", orderRow.Symbol);
                                Decimal executionPrice = 0.0M;
                                if (priceRow != null)
                                {
                                    executionPrice = orderRow.SideCode == SideCode.Buy || orderRow.SideCode == SideCode.BuyCover ?
                                                     priceRow.BidPrice :
                                                     priceRow.AskPrice;
                                }
                                Guid executionId        = Guid.NewGuid();
                                Guid destinationOrderId = orderRow.DestinationOrderId;

                                // When the order is completed, it is removed from the order book.  When the order book is empty, the thread goes to sleep
                                // until another thread puts something in the order queue.
                                orderRow.QuantityExecuted += quantityExecuted;
                                if (orderRow.QuantityOrdered == orderRow.QuantityExecuted)
                                {
                                    MarketSimulator.dataSetMarket.Order.RemoveOrderRow(orderRow);
                                    if (MarketSimulator.dataSetMarket.Order.Count == 0)
                                    {
                                        MarketSimulator.orderEvent.Reset();
                                    }
                                }

                                if (quantityExecuted > 0)
                                {
                                    Monitor.Exit(MarketSimulator.syncRoot);

                                    dataModel.CreateExecution(
                                        0.0M,
                                        blotterId,
                                        null,
                                        brokerId,
                                        0.0M,
                                        dateTime,
                                        userId,
                                        destinationOrderId,
                                        StateMap.FromCode(StateCode.Acknowledged),
                                        executionId,
                                        executionPrice,
                                        quantityExecuted,
                                        null,
                                        null,
                                        false,
                                        dateTime,
                                        userId,
                                        null,
                                        null,
                                        null,
                                        null,
                                        StateMap.FromCode(StateCode.Acknowledged),
                                        0.0M,
                                        0.0M,
                                        0.0M,
                                        0.0M);
                                    Monitor.Enter(MarketSimulator.syncRoot);
                                }

                                break;
                            }

                            // This will commit the changes to the order book.
                            transactionScope.Complete();
                        }

                        // This allows another thread to work the order.
                        orderRow.IsBusy = false;
                    }
                }
                finally
                {
                    Monitor.Exit(MarketSimulator.syncRoot);
                }

                // This allows other threads the chance to run.
                Thread.Sleep(0);
            }
        }