예제 #1
0
        public string HelloIndigo(string s)
        {
            AuthorizationContext authContext =
                ServiceSecurityContext.Current.AuthorizationContext;

            X509CertificateClaimSet certClaims = null;

            foreach (ClaimSet c in authContext.ClaimSets)
            {
                certClaims = c as X509CertificateClaimSet;
                if (certClaims != null)
                {
                    break;
                }
            }
            if (certClaims == null)
            {
                throw new SecurityException("Access is denied. X509CertificateClaimSet is required.");
            }

            if (!certClaims.ContainsClaim(
                    Claim.CreateDnsClaim(s)))
            {
                throw new SecurityException("Access is denied.");
            }

            return(string.Format("Checked certificate against DNS claim for '{0}' at {1}", s, DateTime.Now));
        }
예제 #2
0
        private static X509Certificate2 RetrieveClientCertificate(HttpRequestMessage request)
        {
            if (request == null)
            {
                throw Error.ArgumentNull("request");
            }

            SecurityMessageProperty property = request.GetSecurityMessageProperty();
            X509Certificate2        result   = null;

            if (property != null && property.ServiceSecurityContext != null && property.ServiceSecurityContext.AuthorizationContext != null)
            {
                X509CertificateClaimSet certClaimSet = null;
                foreach (ClaimSet claimSet in property.ServiceSecurityContext.AuthorizationContext.ClaimSets)
                {
                    certClaimSet = claimSet as X509CertificateClaimSet;

                    if (certClaimSet != null)
                    {
                        result = certClaimSet.X509Certificate;
                        break;
                    }
                }
            }

            return(result);
        }
예제 #3
0
        public override bool CheckAccess(EndpointIdentity identity, AuthorizationContext authContext)
        {
            List <Claim>  claims = new List <Claim>();
            X509Extension item   = null;

            foreach (ClaimSet claimSet in authContext.ClaimSets)
            {
                if (item == null)
                {
                    X509CertificateClaimSet x509CertificateClaimSet = claimSet as X509CertificateClaimSet;
                    if (x509CertificateClaimSet != null && x509CertificateClaimSet.X509Certificate != null)
                    {
                        item = x509CertificateClaimSet.X509Certificate.Extensions["2.5.29.17"];
                    }
                }
                foreach (Claim claim in claimSet)
                {
                    if (ClaimTypes.Dns != claim.ClaimType)
                    {
                        continue;
                    }
                    claims.Add(claim);
                }
            }
            if (1 != claims.Count)
            {
                throw new InvalidOperationException(SRClient.InvalidDNSClaims(claims.Count));
            }
            if (LenientDnsIdentityVerifier.CheckTopLevelDomainCompatibleness(claims[0].Resource.ToString(), identity.IdentityClaim.Resource.ToString()))
            {
                return(true);
            }
            return(SecureSocketUtil.CertificateCheckSubjectAlternativeNames(item, identity.IdentityClaim.Resource.ToString()));
        }
        [Ignore("not up to date")]          // X509Chain
        public void DefaultValues()
        {
            X509Chain chain = new X509Chain();

            chain.Build(cert);
            Assert.IsTrue(chain.ChainElements.Count > 1, "#0");
            ClaimSet cs    = new X509CertificateClaimSet(cert);
            ClaimSet ident = cs.Issuer;
            X509CertificateClaimSet x509is = ident as X509CertificateClaimSet;

            Assert.IsNotNull(x509is, "#0-2");
            Assert.AreEqual(chain.ChainElements [1].Certificate, x509is.X509Certificate, "#0-3");
            Assert.AreEqual(6, cs.Count, "#1");
            Assert.AreEqual(6, ident.Issuer.Count, "#2");
            Assert.IsFalse(cs.ContainsClaim(Claim.System), "#3");
            List <string> d = new List <string> ();

            foreach (Claim c in cs)
            {
                if (c.ClaimType != ClaimTypes.Thumbprint)
                {
                    Assert.AreEqual(Rights.PossessProperty, c.Right, "#4");
                }
                d.Add(c.ClaimType);
            }
            Assert.IsTrue(d.Contains(ClaimTypes.X500DistinguishedName), "#5");
            Assert.IsTrue(d.Contains(ClaimTypes.Thumbprint), "#6");
            Assert.IsTrue(d.Contains(ClaimTypes.Dns), "#7");
            Assert.IsTrue(d.Contains(ClaimTypes.Rsa), "#8");
            Assert.IsTrue(d.Contains(ClaimTypes.Name), "#9");
        }
예제 #5
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();
        }
예제 #6
0
        protected override ReadOnlyCollection <IAuthorizationPolicy> ValidateTokenCore(SecurityToken token)
        {
            X509SecurityToken x509Token = (X509SecurityToken)token;

            this.validator.Validate(x509Token.Certificate);

            X509CertificateClaimSet x509ClaimSet = new X509CertificateClaimSet(x509Token.Certificate, this.cloneHandle);

            if (!this.mapToWindows)
            {
                return(SecurityUtils.CreateAuthorizationPolicies(x509ClaimSet, x509Token.ValidTo));
            }

            WindowsClaimSet windowsClaimSet;

            if (token is X509WindowsSecurityToken)
            {
                windowsClaimSet = new WindowsClaimSet(((X509WindowsSecurityToken)token).WindowsIdentity, SecurityUtils.AuthTypeCertMap, this.includeWindowsGroups, this.cloneHandle);
            }
            else
            {
                // Ensure NT_AUTH chain policy for certificate account mapping
                X509CertificateValidator.NTAuthChainTrust.Validate(x509Token.Certificate);

                WindowsIdentity windowsIdentity = null;
                // for Vista, LsaLogon supporting mapping cert to NTToken
                if (Environment.OSVersion.Version.Major >= SecurityUtils.WindowsVistaMajorNumber)
                {
                    windowsIdentity = KerberosCertificateLogon(x509Token.Certificate);
                }
                else
                {
                    // Downlevel, S4U over PrincipalName SubjectAltNames
                    string name = x509Token.Certificate.GetNameInfo(X509NameType.UpnName, false);
                    if (string.IsNullOrEmpty(name))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenValidationException(SR.GetString(SR.InvalidNtMapping,
                                                                                                                                    SecurityUtils.GetCertificateId(x509Token.Certificate))));
                    }

                    using (WindowsIdentity initialWindowsIdentity = new WindowsIdentity(name, SecurityUtils.AuthTypeCertMap))
                    {
                        // This is to make sure that the auth Type is shoved down to the class as the above constructor does not do it.
                        windowsIdentity = new WindowsIdentity(initialWindowsIdentity.Token, SecurityUtils.AuthTypeCertMap);
                    }
                }

                windowsClaimSet = new WindowsClaimSet(windowsIdentity, SecurityUtils.AuthTypeCertMap, this.includeWindowsGroups, false);
            }
            List <ClaimSet> claimSets = new List <ClaimSet>(2);

            claimSets.Add(windowsClaimSet);
            claimSets.Add(x509ClaimSet);

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

            policies.Add(new UnconditionalPolicy(claimSets.AsReadOnly(), x509Token.ValidTo));
            return(policies.AsReadOnly());
        }
예제 #7
0
 internal static EndpointIdentity GetServiceCertificateIdentity(X509Certificate2 certificate)
 {
     using (X509CertificateClaimSet claimSet = new X509CertificateClaimSet(certificate))
     {
         EndpointIdentity identity;
         if (!TryCreateIdentity(claimSet, ClaimTypes.Dns, out identity))
         {
             TryCreateIdentity(claimSet, ClaimTypes.Rsa, out identity);
         }
         return(identity);
     }
 }
예제 #8
0
        public static void SerializeClaimSet(ClaimSet claimSet, SctClaimDictionary dictionary, XmlDictionaryWriter writer, XmlObjectSerializer serializer, XmlObjectSerializer claimSerializer)
        {
            if (claimSet is X509CertificateClaimSet)
            {
                X509CertificateClaimSet x509ClaimSet = (X509CertificateClaimSet)claimSet;
                writer.WriteStartElement(dictionary.X509CertificateClaimSet, dictionary.EmptyString);
                byte[] rawData = x509ClaimSet.X509Certificate.RawData;
                writer.WriteBase64(rawData, 0, rawData.Length);
                writer.WriteEndElement();
            }
            else if (claimSet == ClaimSet.System)
            {
                writer.WriteElementString(dictionary.SystemClaimSet, dictionary.EmptyString, String.Empty);
            }
            else if (claimSet == ClaimSet.Windows)
            {
                writer.WriteElementString(dictionary.WindowsClaimSet, dictionary.EmptyString, String.Empty);
            }
            else if (claimSet == ClaimSet.Anonymous)
            {
                writer.WriteElementString(dictionary.AnonymousClaimSet, dictionary.EmptyString, String.Empty);
            }
            else if (claimSet is WindowsClaimSet || claimSet is DefaultClaimSet)
            {
                writer.WriteStartElement(dictionary.ClaimSet, dictionary.EmptyString);
                writer.WriteStartElement(dictionary.PrimaryIssuer, dictionary.EmptyString);
                if (claimSet.Issuer == claimSet)
                {
                    writer.WriteElementString(dictionary.NullValue, dictionary.EmptyString, string.Empty);
                }
                else
                {
                    SerializeClaimSet(claimSet.Issuer, dictionary, writer, serializer, claimSerializer);
                }
                writer.WriteEndElement();

                foreach (Claim claim in claimSet)
                {
                    writer.WriteStartElement(dictionary.Claim, dictionary.EmptyString);
                    SerializeClaim(claim, dictionary, writer, claimSerializer);
                    writer.WriteEndElement();
                }
                writer.WriteEndElement();
            }
            else
            {
                serializer.WriteObject(writer, claimSet);
            }
        }
        protected override ReadOnlyCollection <IAuthorizationPolicy> ValidateTokenCore(SecurityToken token)
        {
            WindowsClaimSet   set2;
            X509SecurityToken token2 = (X509SecurityToken)token;

            this.validator.Validate(token2.Certificate);
            X509CertificateClaimSet claimSet = new X509CertificateClaimSet(token2.Certificate, this.cloneHandle);

            if (!this.mapToWindows)
            {
                return(System.IdentityModel.SecurityUtils.CreateAuthorizationPolicies(claimSet, token2.ValidTo));
            }
            if (token is X509WindowsSecurityToken)
            {
                set2 = new WindowsClaimSet(((X509WindowsSecurityToken)token).WindowsIdentity, "SSL/PCT", this.includeWindowsGroups, this.cloneHandle);
            }
            else
            {
                X509CertificateValidator.NTAuthChainTrust.Validate(token2.Certificate);
                WindowsIdentity windowsIdentity = null;
                if (Environment.OSVersion.Version.Major >= 6)
                {
                    windowsIdentity = KerberosCertificateLogon(token2.Certificate);
                }
                else
                {
                    string nameInfo = token2.Certificate.GetNameInfo(X509NameType.UpnName, false);
                    if (string.IsNullOrEmpty(nameInfo))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenValidationException(System.IdentityModel.SR.GetString("InvalidNtMapping", new object[] { System.IdentityModel.SecurityUtils.GetCertificateId(token2.Certificate) })));
                    }
                    using (WindowsIdentity identity2 = new WindowsIdentity(nameInfo, "SSL/PCT"))
                    {
                        windowsIdentity = new WindowsIdentity(identity2.Token, "SSL/PCT");
                    }
                }
                set2 = new WindowsClaimSet(windowsIdentity, "SSL/PCT", this.includeWindowsGroups, false);
            }
            List <ClaimSet> list = new List <ClaimSet>(2)
            {
                set2,
                claimSet
            };

            return(new List <IAuthorizationPolicy>(1)
            {
                new UnconditionalPolicy(list.AsReadOnly(), token2.ValidTo)
            }.AsReadOnly());
        }
예제 #10
0
        private bool IsCertificateAuthentication(OperationContext operationContext)
        {
            if (!ConfigBase <MRSConfigSchema> .GetConfig <bool>("ProxyServiceCertificateEndpointEnabled"))
            {
                return(false);
            }
            ServiceSecurityContext serviceSecurityContext = operationContext.ServiceSecurityContext;

            if (serviceSecurityContext == null || serviceSecurityContext.AuthorizationContext == null || serviceSecurityContext.AuthorizationContext.ClaimSets == null || serviceSecurityContext.AuthorizationContext.ClaimSets.Count != 1)
            {
                return(false);
            }
            X509CertificateClaimSet x509CertificateClaimSet = serviceSecurityContext.AuthorizationContext.ClaimSets[0] as X509CertificateClaimSet;

            return(x509CertificateClaimSet != null && !(x509CertificateClaimSet.X509Certificate.Subject != ConfigBase <MRSConfigSchema> .GetConfig <string>("ProxyClientCertificateSubject")));
        }
        protected override ReadOnlyCollection <IAuthorizationPolicy> ValidateTokenCore(SecurityToken token)
        {
            X509SecurityToken x509Token = (X509SecurityToken)token;

            _validator.Validate(x509Token.Certificate);

            X509CertificateClaimSet x509ClaimSet = new X509CertificateClaimSet(x509Token.Certificate, _cloneHandle);

            if (!_mapToWindows)
            {
                return(SecurityUtils.CreateAuthorizationPolicies(x509ClaimSet, x509Token.ValidTo));
            }
            else
            {
                throw ExceptionHelper.PlatformNotSupported("Mapping to Windows identity not supported.");
            }
        }
예제 #12
0
        protected override ReadOnlyCollection <IAuthorizationPolicy> ValidateTokenCore(SecurityToken token)
        {
            X509SecurityToken x509Token = (X509SecurityToken)token;

            _validator.Validate(x509Token.Certificate);

            X509CertificateClaimSet x509ClaimSet = new X509CertificateClaimSet(x509Token.Certificate, _cloneHandle);

            if (!MapCertificateToWindowsAccount)
            {
                return(SecurityUtils.CreateAuthorizationPolicies(x509ClaimSet, x509Token.ValidTo));
            }

            WindowsClaimSet windowsClaimSet;

            if (token is X509WindowsSecurityToken x509token)
            {
                windowsClaimSet = new WindowsClaimSet(x509token.WindowsIdentity, SecurityUtils.AuthTypeCertMap, _includeWindowsGroups, _cloneHandle);
            }
            else
            {
                throw new PlatformNotSupportedException();
                // Ensure NT_AUTH chain policy for certificate account mapping
                //X509CertificateValidator.NTAuthChainTrust.Validate(x509Token.Certificate);

                //WindowsIdentity windowsIdentity = null;
                //windowsIdentity = KerberosCertificateLogon(x509Token.Certificate);


                //windowsClaimSet = new WindowsClaimSet(windowsIdentity, SecurityUtils.AuthTypeCertMap, this.includeWindowsGroups, false);
            }
            List <ClaimSet> claimSets = new List <ClaimSet>(2)
            {
                windowsClaimSet,
                x509ClaimSet
            };

            List <IAuthorizationPolicy> policies = new List <IAuthorizationPolicy>(1)
            {
                new UnconditionalPolicy(claimSets.AsReadOnly(), x509Token.ValidTo)
            };

            return(policies.AsReadOnly());
        }
        public void TestThatEvaluateSetsPrincipalWithClaimIdentityWithTrustedClaimSetsInPropertiesOnEvaluationContextWhenClaimSetsInEvaluationContextIsNotNull(string certificateSubjectName)
        {
            var certificateClaimSet = new X509CertificateClaimSet(TestHelper.GetCertificate(certificateSubjectName));

            var authorizationHandlerMock = MockRepository.GenerateMock <IAuthorizationHandler>();

            authorizationHandlerMock.Stub(m => m.GetTrustedClaimSets(Arg <IEnumerable <ClaimSet> > .Is.NotNull))
            .Return(new List <ClaimSet> {
                certificateClaimSet
            })
            .Repeat.Any();

            var claimsPrincipalBuilderAuthorizationPolicy = new ClaimsPrincipalBuilderAuthorizationPolicy(authorizationHandlerMock);

            Assert.That(claimsPrincipalBuilderAuthorizationPolicy, Is.Not.Null);

            var properties            = new Dictionary <string, object>(0);
            var evaluationContextStub = MockRepository.GenerateStub <EvaluationContext>();

            evaluationContextStub.Stub(m => m.Properties)
            .Return(properties)
            .Repeat.Any();
            evaluationContextStub.Stub(m => m.ClaimSets)
            .Return(new ReadOnlyCollection <ClaimSet>(new List <ClaimSet> {
                MockRepository.GenerateStub <ClaimSet>()
            }))
            .Repeat.Any();
            var state = CreateLegalState();

            claimsPrincipalBuilderAuthorizationPolicy.Evaluate(evaluationContextStub, ref state);

            var claimPrincipal = (ClaimsPrincipal)properties["Principal"];

            Assert.That(claimPrincipal, Is.Not.Null);
            Assert.That(claimPrincipal.Identity, Is.Not.Null);
            Assert.That(claimPrincipal.Identity, Is.TypeOf <ClaimsIdentity>());
            Assert.That(claimPrincipal.Identities, Is.Not.Null);
            Assert.That(claimPrincipal.Identities, Is.Not.Empty);
            Assert.That(claimPrincipal.Identities.Count, Is.EqualTo(1));
            Assert.That(claimPrincipal.Identities.ElementAt(0), Is.Not.Null);
            Assert.That(claimPrincipal.Identities.ElementAt(0).Claims, Is.Not.Null);
            Assert.That(claimPrincipal.Identities.ElementAt(0).Claims, Is.Not.Empty);
            Assert.That(claimPrincipal.Identities.ElementAt(0).Claims.Count, Is.EqualTo(certificateClaimSet.Count(claim => string.Compare(claim.Right, Rights.PossessProperty, StringComparison.Ordinal) == 0)));
        }
예제 #14
0
        /// <summary>
        /// Application level check for claims at the BookStoreSTS
        /// </summary>
        /// <param name="bookID">ID of the book intended for purchase</param>
        /// <returns>True on success. False on failure.</returns>
        private static bool CheckIfPurchaseLimitMet(string bookID)
        {
            // Extract the AuthorizationContext from the ServiceSecurityContext
            AuthorizationContext authContext = OperationContext.Current.ServiceSecurityContext.AuthorizationContext;

            // If there are no Claims in the AuthorizationContext, return false
            // The issued token used to authenticate should contain claims
            if (authContext.ClaimSets == null)
            {
                return(false);
            }

            // If there is more than two ClaimSets in the AuthorizationContext, return false
            // The issued token used to authenticate should only contain two sets of claims.
            if (authContext.ClaimSets.Count != 2)
            {
                return(false);
            }

            List <ClaimSet> claimsets  = new List <ClaimSet>(authContext.ClaimSets);
            ClaimSet        myClaimSet = claimsets.Find((Predicate <ClaimSet>) delegate(ClaimSet target)
            {
                X509CertificateClaimSet certClaimSet = target.Issuer as X509CertificateClaimSet;
                return(certClaimSet != null && certClaimSet.X509Certificate.Subject == "CN=HomeRealmSTS.com");
            });

            // Is the ClaimSet was NOT issued by the HomeRealmSTS then return false
            // The BookStoreSTS only accepts requests where the client authenticated using a token
            // issued by the HomeRealmSTS.
            if (!IssuedByHomeRealmSTS(myClaimSet))
            {
                return(false);
            }

            // Find all the PurchaseLimit claims
            IEnumerable <Claim> purchaseLimitClaims = myClaimSet.FindClaims(Constants.PurchaseLimitClaim, Rights.PossessProperty);

            // If there are no PurchaseLimit claims, return false
            // The HomeRealmSTS issues tokens containing PurchaseLimit claims for all authorized requests.
            if (purchaseLimitClaims == null)
            {
                return(false);
            }

            // Get the price of the book being purchased...
            double bookPrice = GetBookPrice(bookID);

            // Iterate through the PurchaseLimit claims and verify that the Resource value is
            // greater than or equal to the price of the book being purchased
            foreach (Claim c in purchaseLimitClaims)
            {
                double purchaseLimit = Double.Parse(c.Resource.ToString());
                if (purchaseLimit >= bookPrice)
                {
                    return(true);
                }
            }

            // If no PurchaseLimit claim had a resource value that was greater than or equal
            // to the price of the book being purchased, return false
            return(false);
        }
예제 #15
0
        internal static string GetIdentityNamesFromContext(AuthorizationContext authContext)
        {
            if (authContext == null)
            {
                return(String.Empty);
            }

            StringBuilder str = new StringBuilder(256);

            for (int i = 0; i < authContext.ClaimSets.Count; ++i)
            {
                ClaimSet claimSet = authContext.ClaimSets[i];

                // Windows
                WindowsClaimSet windows = claimSet as WindowsClaimSet;
                if (windows != null)
                {
#if SUPPORTS_WINDOWSIDENTITY
                    if (str.Length > 0)
                    {
                        str.Append(", ");
                    }

                    AppendIdentityName(str, windows.WindowsIdentity);
#else
                    throw ExceptionHelper.PlatformNotSupported(ExceptionHelper.WinsdowsStreamSecurityNotSupported);
#endif // SUPPORTS_WINDOWSIDENTITY
                }
                else
                {
                    // X509
                    X509CertificateClaimSet x509 = claimSet as X509CertificateClaimSet;
                    if (x509 != null)
                    {
                        if (str.Length > 0)
                        {
                            str.Append(", ");
                        }

                        AppendCertificateIdentityName(str, x509.X509Certificate);
                    }
                }
            }

            if (str.Length <= 0)
            {
                List <IIdentity> identities = null;
                object           obj;
                if (authContext.Properties.TryGetValue(SecurityUtils.Identities, out obj))
                {
                    identities = obj as List <IIdentity>;
                }
                if (identities != null)
                {
                    for (int i = 0; i < identities.Count; ++i)
                    {
                        IIdentity identity = identities[i];
                        if (identity != null)
                        {
                            if (str.Length > 0)
                            {
                                str.Append(", ");
                            }

                            AppendIdentityName(str, identity);
                        }
                    }
                }
            }
            return(str.Length <= 0 ? String.Empty : str.ToString());
        }
예제 #16
0
        /// <summary>
        /// Implementation of the framework level access control mechanism via ServiceAuthorizationManager
        /// </summary>
        /// <returns>True on success. False on failure.</returns>
        public override bool CheckAccess(OperationContext operationContext)
        {
            // BrowseBooks is always authorized, so return true
            if (operationContext.IncomingMessageHeaders.Action == ServiceConstants.BrowseBooksAction)
            {
                return(true);
            }

            // If the requested operation is NOT BuyBook, return false (Access Denied)
            // The only operation we support apart from BrowseBooks is BuyBook
            if (operationContext.IncomingMessageHeaders.Action != ServiceConstants.BuyBookAction)
            {
                return(false);
            }

            // Extract the AuthorizationContext from the ServiceSecurityContext
            AuthorizationContext authContext = operationContext.ServiceSecurityContext.AuthorizationContext;

            // If there are no Claims in the AuthorizationContext, return false (Access Denied)
            // The issued token used to authenticate should contain claims
            if (authContext.ClaimSets == null)
            {
                return(false);
            }

            // If there is more than one ClaimSet in the AuthorizationContext, return false (Access Denied).
            // The issued token used to authenticate should only contain a single set of claims.
            if (authContext.ClaimSets.Count != 2)
            {
                return(false);
            }

            // Extract the single ClaimSet from the AuthorizationContext
            List <ClaimSet> claimsets  = new List <ClaimSet>(authContext.ClaimSets);
            ClaimSet        myClaimSet = claimsets.Find((Predicate <ClaimSet>) delegate(ClaimSet target)
            {
                X509CertificateClaimSet certClaimSet = target.Issuer as X509CertificateClaimSet;
                return(certClaimSet != null && certClaimSet.X509Certificate.Subject == "CN=BookStoreSTS.com");
            });

            // Is the ClaimSet was NOT issued by the BookStoreSTS then return false (Access Denied)
            // The BookStoreService only accepts requests where the client authenticated using a token
            // issued by the BookStoreSTS.
            if (!IssuedByBookStoreSTS(myClaimSet))
            {
                return(false);
            }

            // Find all the PurchaseAuthorized claims
            IEnumerable <Claim> purchaseAllowedClaims = myClaimSet.FindClaims(Constants.PurchaseAuthorizedClaim, Rights.PossessProperty);

            // If there are no PurchaseAuthorized claims, return false (Access Denied)
            // The BookStoreSTS issues tokens containing PurchaseAuthorized claims for all authorized requests.
            if (purchaseAllowedClaims == null)
            {
                return(false);
            }

            // Get the book name being purchased...
            string bookName = operationContext.IncomingMessageHeaders.GetHeader <string>(Constants.BookNameHeaderName, Constants.BookNameHeaderNamespace);

            // ..and if it's null or empty, return false (Access Denied)
            if (string.IsNullOrEmpty(bookName))
            {
                return(false);
            }

            // Iterate through the PurchaseAllowed claims and verify that the Resource value is
            // the same as the book name retrieved above
            foreach (Claim claim in purchaseAllowedClaims)
            {
                string authorizedBook = claim.Resource.ToString();
                if (!string.IsNullOrEmpty(authorizedBook) && authorizedBook.Trim().Equals(bookName.Trim(), StringComparison.OrdinalIgnoreCase))
                {
                    return(true);
                }
            }

            // If no PurchaseAllowed claim had a resource value that matched the
            // book name, return false (Access Denied)
            return(false);
        }