Example #1
0
        public GenericXmlSecurityToken Authenticate(ClaimsIdentity identity, string appliesTo)
        {
            var encryptingCert = _configuration.AdfsIntegration.EncryptionCertificate;

            // create new token
            var proof       = CreateProofDescriptor(encryptingCert);
            var outputToken = CreateOutputSamlToken(identity, proof, encryptingCert);

            // turn token into a generic xml security token
            var outputTokenString = outputToken.ToTokenXmlString();

            // create attached and unattached references
            var handler = new SamlSecurityTokenHandler();
            var ar      = handler.CreateSecurityTokenReference(outputToken, true);
            var uar     = handler.CreateSecurityTokenReference(outputToken, false);

            var xmlToken = new GenericXmlSecurityToken(
                GetElement(outputTokenString),
                new BinarySecretSecurityToken(proof.GetKeyBytes()),
                DateTime.UtcNow,
                DateTime.UtcNow.AddHours(1),
                ar,
                uar,
                new ReadOnlyCollection <IAuthorizationPolicy>(new List <IAuthorizationPolicy>()));

            // send to ADFS federation endpoint
            return(RequestFederationToken(xmlToken, appliesTo) as GenericXmlSecurityToken);
        }
        /// <summary>
        /// Gets a GenericXmlSecurityToken that wraps the provided issued token
        /// with the authorization policies necessary.
        /// </summary>
        static GenericXmlSecurityToken WrapWithAuthPolicy(GenericXmlSecurityToken issuedToken,
                                                           SecurityTokenRequirement tokenRequirement)
        {
            EndpointIdentity endpointIdentity = null;

            var issuedTokenRequirement = tokenRequirement as InitiatorServiceModelSecurityTokenRequirement;
            if (issuedTokenRequirement != null)
            {
                EndpointAddress targetAddress = issuedTokenRequirement.TargetAddress;
                if (targetAddress.Uri.IsAbsoluteUri)
                {
                    endpointIdentity = EndpointIdentity.CreateDnsIdentity(targetAddress.Uri.DnsSafeHost);
                }
            }

            ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies
                = GetServiceAuthorizationPolicies(endpointIdentity);

            return new GenericXmlSecurityToken(issuedToken.TokenXml,
                                                issuedToken.ProofToken,
                                                issuedToken.ValidFrom,
                                                issuedToken.ValidTo,
                                                issuedToken.InternalTokenReference,
                                                issuedToken.ExternalTokenReference,
                                                authorizationPolicies);
        }
Example #3
0
        private void OnNegotiationComplete(SspiNegotiationTokenProviderState sspiState, RequestSecurityTokenResponse negotiationRstr, RequestSecurityTokenResponse authenticatorRstr)
        {
            ISspiNegotiation sspiNegotiation = sspiState.SspiNegotiation;
            ReadOnlyCollection <IAuthorizationPolicy> authorizationPolicies = this.ValidateSspiNegotiation(sspiNegotiation);
            SecurityTokenResolver   resolver     = new SspiSecurityTokenResolver(sspiNegotiation);
            GenericXmlSecurityToken serviceToken = negotiationRstr.GetIssuedToken(resolver, System.ServiceModel.Security.EmptyReadOnlyCollection <SecurityTokenAuthenticator> .Instance, SecurityKeyEntropyMode.ServerEntropy, null, base.SecurityContextTokenUri, authorizationPolicies, 0, false);

            if (serviceToken == null)
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(System.ServiceModel.SR.GetString("NoServiceTokenReceived")));
            }
            WrappedKeySecurityToken proofToken = serviceToken.ProofToken as WrappedKeySecurityToken;

            if ((proofToken == null) || (proofToken.WrappingAlgorithm != sspiNegotiation.KeyEncryptionAlgorithm))
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(System.ServiceModel.SR.GetString("ProofTokenWasNotWrappedCorrectly")));
            }
            byte[] wrappedKey = proofToken.GetWrappedKey();
            if (authenticatorRstr == null)
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(System.ServiceModel.SR.GetString("RSTRAuthenticatorNotPresent")));
            }
            byte[] authenticator = authenticatorRstr.GetAuthenticator();
            if (authenticator == null)
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(System.ServiceModel.SR.GetString("RSTRAuthenticatorNotPresent")));
            }
            if (!IsCorrectAuthenticator(sspiState, wrappedKey, authenticator))
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(System.ServiceModel.SR.GetString("RSTRAuthenticatorIncorrect")));
            }
            sspiState.SetServiceToken(serviceToken);
        }
Example #4
0
        private SecurityToken RequestFederationToken(GenericXmlSecurityToken xmlToken, string appliesTo)
        {
            var adfsEndpoint = _configuration.AdfsIntegration.FederationEndpoint;

            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                AppliesTo   = new EndpointReference(appliesTo),
                KeyType     = KeyTypes.Bearer
            };

            var binding = new IssuedTokenWSTrustBinding();

            binding.SecurityMode = SecurityMode.TransportWithMessageCredential;

            var factory = new WSTrustChannelFactory(
                binding,
                new EndpointAddress(adfsEndpoint));

            factory.TrustVersion = TrustVersion.WSTrust13;
            factory.Credentials.SupportInteractive = false;

            var channel = factory.CreateChannelWithIssuedToken(xmlToken);

            return(channel.Issue(rst));
        }
        internal bool MatchesGenericXmlTokenKeyIdentifierClause(SecurityToken token, SecurityKeyIdentifierClause keyIdentifierClause, SecurityTokenReferenceStyle referenceStyle)
        {
            if (token == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token");
            }

            bool result;

            GenericXmlSecurityToken xmlToken = token as GenericXmlSecurityToken;

            if (xmlToken == null)
            {
                result = false;
            }
            else if (referenceStyle == SecurityTokenReferenceStyle.External && xmlToken.ExternalTokenReference != null)
            {
                result = xmlToken.ExternalTokenReference.Matches(keyIdentifierClause);
            }
            else if (referenceStyle == SecurityTokenReferenceStyle.Internal)
            {
                result = xmlToken.MatchesKeyIdentifierClause(keyIdentifierClause);
            }
            else
            {
                result = false;
            }

            return(result);
        }
        private HttpResponseMessage CreateTokenResponse(GenericXmlSecurityToken token, string scope)
        {
            var response = new TokenResponse();

            if (ConfigurationRepository.AdfsIntegration.PassThruAuthenticationToken)
            {
                response.AccessToken = token.TokenXml.OuterXml;
                response.ExpiresIn   = (int)(token.ValidTo.Subtract(DateTime.UtcNow).TotalSeconds);
            }
            else
            {
                var bridge = new AdfsBridge(ConfigurationRepository);
                if (ConfigurationRepository.Keys.DecryptionCertificate != null)
                {
                    var configuration = new SecurityTokenHandlerConfiguration
                    {
                        AudienceRestriction       = { AudienceMode = AudienceUriMode.Never },
                        CertificateValidationMode = X509CertificateValidationMode.None,
                        RevocationMode            = X509RevocationMode.NoCheck,
                        CertificateValidator      = X509CertificateValidator.None,
                        ServiceTokenResolver      = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
                            new ReadOnlyCollection <SecurityToken>(new SecurityToken[] { new X509SecurityToken(ConfigurationRepository.Keys.DecryptionCertificate) }), false)
                    };
                    var handler = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(configuration);
                    response = bridge.ConvertSamlToJwt(token.ToSecurityToken(handler), scope);
                }
                else
                {
                    response = bridge.ConvertSamlToJwt(token.ToSecurityToken(), scope);
                }
            }

            return(Request.CreateResponse <TokenResponse>(HttpStatusCode.OK, response));
        }
Example #7
0
        // Since the issued token is an endorsing token it will not be used for identity checks
        // hence we do not need to persist the authorization policies that represent the target service.
        static void SerializeCachedToken(Stream stream, Uri target, Uri issuer, GenericXmlSecurityToken token)
        {
            XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8);

            writer.WriteStartElement("Entry");
            writer.WriteElementString("Target", target.AbsoluteUri);
            writer.WriteElementString("Issuer", (issuer == null) ? "" : issuer.AbsoluteUri);

            writer.WriteStartElement("Token");
            writer.WriteStartElement("XML");
            token.TokenXml.WriteTo(writer);
            writer.WriteEndElement();
            SymmetricSecurityKey key = (SymmetricSecurityKey)(token.SecurityKeys[0]);

            writer.WriteElementString("Key", Convert.ToBase64String(key.GetSymmetricKey()));
            writer.WriteElementString("Id", token.Id);
            writer.WriteElementString("ValidFrom", Convert.ToString(token.ValidFrom));
            writer.WriteElementString("ValidTo", Convert.ToString(token.ValidTo));
            WSSecurityTokenSerializer serializer = new WSSecurityTokenSerializer();

            writer.WriteStartElement("InternalTokenReference");
            serializer.WriteKeyIdentifierClause(writer, token.InternalTokenReference);
            writer.WriteEndElement();
            writer.WriteStartElement("ExternalTokenReference");
            serializer.WriteKeyIdentifierClause(writer, token.ExternalTokenReference);
            writer.WriteEndElement();

            writer.WriteEndElement(); // token
            writer.WriteEndElement(); // entry

            writer.Flush();
            stream.Flush();
        }
Example #8
0
        private static void PopulateCache(Dictionary <IssuedTokenCacheBase.Key, GenericXmlSecurityToken> cache, Stream stream)
        {
            XmlTextReader xmlTextReader = new XmlTextReader(stream);

            while (xmlTextReader.IsStartElement("Entry"))
            {
                xmlTextReader.ReadStartElement();
                Uri    target = new Uri(xmlTextReader.ReadElementString("Target"));
                string text   = xmlTextReader.ReadElementString("Issuer");
                Uri    issuer = string.IsNullOrEmpty(text) ? null : new Uri(text);
                xmlTextReader.ReadStartElement("Token");
                xmlTextReader.ReadStartElement("XML");
                XmlDocument xmlDocument = new XmlDocument();
                XmlElement  tokenXml    = xmlDocument.ReadNode(xmlTextReader) as XmlElement;
                xmlTextReader.ReadEndElement();
                byte[] key = Convert.FromBase64String(xmlTextReader.ReadElementString("Key"));
                xmlTextReader.ReadElementString("Id");
                DateTime effectiveTime  = Convert.ToDateTime(xmlTextReader.ReadElementString("ValidFrom"));
                DateTime expirationTime = Convert.ToDateTime(xmlTextReader.ReadElementString("ValidTo"));
                WSSecurityTokenSerializer wssecurityTokenSerializer = new WSSecurityTokenSerializer();
                xmlTextReader.ReadStartElement("InternalTokenReference");
                SecurityKeyIdentifierClause internalTokenReference = wssecurityTokenSerializer.ReadKeyIdentifierClause(xmlTextReader);
                xmlTextReader.ReadEndElement();
                xmlTextReader.ReadStartElement("ExternalTokenReference");
                SecurityKeyIdentifierClause externalTokenReference = wssecurityTokenSerializer.ReadKeyIdentifierClause(xmlTextReader);
                xmlTextReader.ReadEndElement();
                xmlTextReader.ReadEndElement();
                xmlTextReader.ReadEndElement();
                List <IAuthorizationPolicy> list  = new List <IAuthorizationPolicy>();
                GenericXmlSecurityToken     value = new GenericXmlSecurityToken(tokenXml, new BinarySecretSecurityToken(key), effectiveTime, expirationTime, internalTokenReference, externalTokenReference, new ReadOnlyCollection <IAuthorizationPolicy>(list));
                cache.Add(new IssuedTokenCacheBase.Key(target, issuer), value);
            }
        }
Example #9
0
 public override bool TryGetToken(EndpointAddress target, EndpointAddress issuer, out GenericXmlSecurityToken cachedToken)
 {
     if (target == null)
     {
         throw new ArgumentNullException("target");
     }
     cachedToken = null;
     lock (thisLock)
     {
         GenericXmlSecurityToken tmp;
         Key key = new Key(target.Uri, issuer == null ? null : issuer.Uri);
         if (this.cache.TryGetValue(key, out tmp))
         {
             // if the cached token is going to expire soon, remove it from the cache and return a cache miss
             if (tmp.ValidTo < DateTime.UtcNow + TimeSpan.FromMinutes(1))
             {
                 this.cache.Remove(key);
                 OnTokenRemoved(key);
             }
             else
             {
                 cachedToken = tmp;
             }
         }
     }
     return (cachedToken != null);
 }
        public GenericXmlSecurityToken Authenticate(ClaimsIdentity identity, string appliesTo)
        {
            var encryptingCert = _configuration.AdfsIntegration.EncryptionCertificate;

            // create new token
            var proof = CreateProofDescriptor(encryptingCert);
            var outputToken = CreateOutputSamlToken(identity, proof, encryptingCert);

            // turn token into a generic xml security token
            var outputTokenString = outputToken.ToTokenXmlString();

            // create attached and unattached references
            var handler = new SamlSecurityTokenHandler();
            var ar = handler.CreateSecurityTokenReference(outputToken, true);
            var uar = handler.CreateSecurityTokenReference(outputToken, false);

            var xmlToken = new GenericXmlSecurityToken(
                GetElement(outputTokenString),
                new BinarySecretSecurityToken(proof.GetKeyBytes()),
                DateTime.UtcNow,
                DateTime.UtcNow.AddHours(1),
                ar,
                uar,
                new ReadOnlyCollection<IAuthorizationPolicy>(new List<IAuthorizationPolicy>()));

            // send to ADFS federation endpoint
            return RequestFederationToken(xmlToken, appliesTo) as GenericXmlSecurityToken;
        }
Example #11
0
        static GenericXmlSecurityToken WrapJwt(string jwt)
        {
            var subject = new ClaimsIdentity("saml");

            subject.AddClaim(new Claim("jwt", jwt));

            var descriptor = new SecurityTokenDescriptor
            {
                TokenType       = TokenTypes.Saml2TokenProfile11,
                TokenIssuerName = "urn:wrappedjwt",
                Subject         = subject
            };

            var handler = new Saml2SecurityTokenHandler();
            var token   = handler.CreateToken(descriptor);

            var xmlToken = new GenericXmlSecurityToken(
                XElement.Parse(token.ToTokenXmlString()).ToXmlElement(),
                null,
                DateTime.Now,
                DateTime.Now.AddHours(1),
                null,
                null,
                null);

            return(xmlToken);
        }
        public GenericXmlSecurityToken DeserializeTokenFromRstr(RequestSecurityTokenResponse rstr)
        {
            SecurityToken proofKey = null;
            DateTime?     created  = null;
            DateTime?     expires  = null;

            if (rstr.Lifetime != null)
            {
                created = rstr.Lifetime.Created;
                expires = rstr.Lifetime.Expires;
            }
            if (!created.HasValue)
            {
                throw new Exception("Created unspecified");
            }
            if (!expires.HasValue)
            {
                throw new Exception("Expires unspecified");
            }

            GenericXmlSecurityToken securityToken = new GenericXmlSecurityToken(
                rstr.RequestedSecurityToken.SecurityTokenXml,
                proofKey,
                created.Value,
                expires.Value,
                rstr.RequestedAttachedReference,
                rstr.RequestedUnattachedReference,
                new ReadOnlyCollection <IAuthorizationPolicy>(new List <IAuthorizationPolicy>())
                );

            return(securityToken);
        }
    public static void Ctor_Default_Properties()
    {
        XmlDocument  doc       = new XmlDocument();
        XmlElement   tokenXml  = doc.CreateElement("ElementName");
        XmlAttribute attr      = doc.CreateAttribute("Id", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
        string       attrValue = "Value for Attribute Name Id";

        attr.Value = attrValue;
        tokenXml.Attributes.Append(attr);
        UserNameSecurityToken proofToken = new UserNameSecurityToken("user", "password");

        GenericXmlSecurityToken gxst = new GenericXmlSecurityToken(tokenXml, proofToken, DateTime.UtcNow, DateTime.MaxValue, null, null, null);

        Assert.NotNull(gxst);
        Assert.NotNull(gxst.Id);
        Assert.Equal(attrValue, gxst.Id);
        Assert.Equal(DateTime.UtcNow.Date, gxst.ValidFrom.Date);
        Assert.Equal(DateTime.MaxValue.Date, gxst.ValidTo.Date);
        Assert.NotNull(gxst.SecurityKeys);
        Assert.Equal(proofToken.SecurityKeys, gxst.SecurityKeys);

        //ProofToken is null
        GenericXmlSecurityToken gxst2 = new GenericXmlSecurityToken(tokenXml, null, DateTime.MinValue, DateTime.MaxValue, null, null, null);

        Assert.NotNull(gxst2.SecurityKeys);
        Assert.Equal(new ReadOnlyCollection <SecurityKey>(new List <SecurityKey>()), gxst2.SecurityKeys);

        //TokenXml is null
        Assert.Throws <System.ArgumentNullException>(() => new GenericXmlSecurityToken(null, null, DateTime.MinValue, DateTime.MaxValue, null, null, null));
    }
Example #14
0
 protected override void ValidateKeySize(GenericXmlSecurityToken issuedToken)
 {
     if (this.keyType != SecurityKeyType.BearerKey)
     {
         base.ValidateKeySize(issuedToken);
     }
 }
        static GenericXmlSecurityToken WrapJwt(string jwt)
        {
            var subject = new ClaimsIdentity("saml");
            subject.AddClaim(new Claim("jwt", jwt));

            var descriptor = new SecurityTokenDescriptor
            {
                TokenType = TokenTypes.Saml2TokenProfile11,
                TokenIssuerName = "urn:wrappedjwt",
                Subject = subject
            };

            var handler = new Saml2SecurityTokenHandler();
            var token = handler.CreateToken(descriptor);

            var xmlToken = new GenericXmlSecurityToken(
                XElement.Parse(token.ToTokenXmlString()).ToXmlElement(),
                null,
                DateTime.Now,
                DateTime.Now.AddHours(1),
                null,
                null,
                null);

            return xmlToken;
        }
        protected virtual void ValidateKeySize(GenericXmlSecurityToken issuedToken)
        {
            if (SecurityAlgorithmSuite == null)
            {
                return;
            }

            ReadOnlyCollection <SecurityKey> issuedKeys = issuedToken.SecurityKeys;

            if (issuedKeys != null && issuedKeys.Count == 1)
            {
                SymmetricSecurityKey symmetricKey = issuedKeys[0] as SymmetricSecurityKey;
                if (symmetricKey != null)
                {
                    if (SecurityAlgorithmSuite.IsSymmetricKeyLengthSupported(symmetricKey.KeySize))
                    {
                        return;
                    }
                    else
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(SR.Format(SR.InvalidIssuedTokenKeySize, symmetricKey.KeySize)));
                    }
                }
            }
            else
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(SR.Format(SR.CannotObtainIssuedTokenKeySize)));
            }
        }
Example #17
0
        /// <summary>
        /// Gets a GenericXmlSecurityToken that wraps the provided issued token
        /// with the authorization policies necessary.
        /// </summary>
        static GenericXmlSecurityToken WrapWithAuthPolicy(GenericXmlSecurityToken issuedToken,
                                                          SecurityTokenRequirement tokenRequirement)
        {
            EndpointIdentity endpointIdentity = null;

            var issuedTokenRequirement = tokenRequirement as InitiatorServiceModelSecurityTokenRequirement;

            if (issuedTokenRequirement != null)
            {
                EndpointAddress targetAddress = issuedTokenRequirement.TargetAddress;
                if (targetAddress.Uri.IsAbsoluteUri)
                {
                    endpointIdentity = EndpointIdentity.CreateDnsIdentity(targetAddress.Uri.DnsSafeHost);
                }
            }

            ReadOnlyCollection <IAuthorizationPolicy> authorizationPolicies
                = GetServiceAuthorizationPolicies(endpointIdentity);

            return(new GenericXmlSecurityToken(issuedToken.TokenXml,
                                               issuedToken.ProofToken,
                                               issuedToken.ValidFrom,
                                               issuedToken.ValidTo,
                                               issuedToken.InternalTokenReference,
                                               issuedToken.ExternalTokenReference,
                                               authorizationPolicies));
        }
        /// <summary>Turns a supported generic XML security token into a security token.</summary>
        /// <param name="token">The generic XML security token.</param>
        /// <returns>A SecurityToken</returns>
        public static SecurityToken ToSecurityToken(this GenericXmlSecurityToken token)
        {
            SecurityTokenHandlerCollection handlerCollection =
                SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection();

            return(token.ToSecurityToken(handlerCollection));
        }
        protected void ValidateKeySize(GenericXmlSecurityToken issuedToken)
        {
            this.CommunicationObject.ThrowIfClosedOrNotOpen();
            ReadOnlyCollection <SecurityKey> issuedKeys = issuedToken.SecurityKeys;

            if (issuedKeys != null && issuedKeys.Count == 1)
            {
                SymmetricSecurityKey symmetricKey = issuedKeys[0] as SymmetricSecurityKey;
                if (symmetricKey != null)
                {
                    if (this.SecurityAlgorithmSuite.IsSymmetricKeyLengthSupported(symmetricKey.KeySize))
                    {
                        return;
                    }
                    else
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(SR.GetString(SR.InvalidIssuedTokenKeySize, symmetricKey.KeySize)));
                    }
                }
            }
            else
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(SR.GetString(SR.CannotObtainIssuedTokenKeySize)));
            }
        }
Example #20
0
        static SecurityToken ConvertToken(TokenResponse response)
        {
            if (response.Error == null)
            {
                XmlDocument document = new XmlDocument();
                XmlElement  element  = document.CreateElement("o", "BinarySecurityToken", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
                element.SetAttribute("ValueType", "urn:ietf:params:oauth:token-type:jwt");
                element.SetAttribute("EncodingType", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary");
                element.SetAttribute("Id", Guid.NewGuid().ToString());
                UTF8Encoding encoding = new UTF8Encoding();
                element.InnerText = Convert.ToBase64String(encoding.GetBytes(response.AccessToken));

                GenericXmlSecurityToken token = new GenericXmlSecurityToken(
                    element,
                    null,
                    DateTime.Now.AddDays(-10),
                    DateTime.Now.AddDays(10),
                    null,
                    null,
                    null);


                return(token);
            }

            return(null);
        }
Example #21
0
        private ClaimsPrincipal ParseToken(GenericXmlSecurityToken genericToken)
        {
            using (XmlReader samlReader = XmlReader.Create(new StringReader(genericToken.TokenXml.OuterXml)))
            {
                SecurityTokenHandlerCollection tokenHandlers = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection();

                SecurityTokenHandlerConfiguration config = tokenHandlers.Configuration;
                var securityTokens = new List <SecurityToken>
                {
                    new X509SecurityToken(CertificateHelper.GetCertificate(_tokenClientOptions.StoreName, _tokenClientOptions.StoreLocation, _tokenClientOptions.SubjectDistinguishedName))
                };

                config.ServiceTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(securityTokens.AsReadOnly(), false);
                config.CertificateValidator = X509CertificateValidator.PeerOrChainTrust;

                config.IssuerTokenResolver = new X509CertificateStoreTokenResolver(_tokenClientOptions.StoreName, _tokenClientOptions.StoreLocation);
                config.IssuerNameRegistry  = _nameRegistry;

                config.AudienceRestriction.AllowedAudienceUris.Add(_tokenClientOptions.AudienceUri);
                SecurityToken samlToken = tokenHandlers.ReadToken(samlReader);

                ClaimsIdentity tokenIdentity = tokenHandlers.ValidateToken(samlToken).FirstOrDefault();
                return(new ClaimsPrincipal(tokenIdentity));
            }
        }
        protected override BodyWriter GetNextOutgoingMessageBody(Message incomingMessage, AcceleratedTokenProviderState negotiationState)
        {
            ThrowIfFault(incomingMessage, TargetAddress);
            if (incomingMessage.Headers.Action != RequestSecurityTokenResponseAction.Value)
            {
                throw TraceUtility.ThrowHelperError(new SecurityNegotiationException(SR.Format(SR.InvalidActionForNegotiationMessage, incomingMessage.Headers.Action)), incomingMessage);
            }
            // get the claims corresponding to the server
            SecurityMessageProperty serverContextProperty = incomingMessage.Properties.Security;
            ReadOnlyCollection <IAuthorizationPolicy> authorizationPolicies;

            if (serverContextProperty != null && serverContextProperty.ServiceSecurityContext != null)
            {
                authorizationPolicies = serverContextProperty.ServiceSecurityContext.AuthorizationPolicies;
            }
            else
            {
                authorizationPolicies = EmptyReadOnlyCollection <IAuthorizationPolicy> .Instance;
            }
            RequestSecurityTokenResponse rstr       = null;
            XmlDictionaryReader          bodyReader = incomingMessage.GetReaderAtBodyContents();

            using (bodyReader)
            {
                if (StandardsManager.MessageSecurityVersion.TrustVersion == TrustVersion.WSTrustFeb2005)
                {
                    rstr = RequestSecurityTokenResponse.CreateFrom(StandardsManager, bodyReader);
                }
                else if (StandardsManager.MessageSecurityVersion.TrustVersion == TrustVersion.WSTrust13)
                {
                    RequestSecurityTokenResponseCollection rstrc = StandardsManager.TrustDriver.CreateRequestSecurityTokenResponseCollection(bodyReader);

                    foreach (RequestSecurityTokenResponse rstrItem in rstrc.RstrCollection)
                    {
                        if (rstr != null)
                        {
                            // More than one RSTR is found. So throw an exception.
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.MoreThanOneRSTRInRSTRC));
                        }
                        rstr = rstrItem;
                    }
                }
                else
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
                }

                incomingMessage.ReadFromBodyContentsToEnd(bodyReader);
            }
            if (rstr.Context != negotiationState.Context)
            {
                throw TraceUtility.ThrowHelperError(new SecurityNegotiationException(SR.BadSecurityNegotiationContext), incomingMessage);
            }
            byte[] keyEntropy = negotiationState.GetRequestorEntropy();
            GenericXmlSecurityToken serviceToken = rstr.GetIssuedToken(null, null, _keyEntropyMode, keyEntropy, SecurityContextTokenUri, authorizationPolicies, SecurityAlgorithmSuite.DefaultSymmetricKeyLength, false);

            negotiationState.SetServiceToken(serviceToken);
            return(null);
        }
Example #23
0
        private GenericXmlSecurityToken ExtractToken(Message response, object requestState)
        {
            // get the claims corresponding to the server
            SecurityMessageProperty serverContextProperty = response.Properties.Security;
            ReadOnlyCollection <IAuthorizationPolicy> authorizationPolicies;

            if (serverContextProperty != null && serverContextProperty.ServiceSecurityContext != null)
            {
                authorizationPolicies = serverContextProperty.ServiceSecurityContext.AuthorizationPolicies;
            }
            else
            {
                authorizationPolicies = EmptyReadOnlyCollection <IAuthorizationPolicy> .Instance;
            }

            RequestSecurityTokenResponse rstr       = null;
            XmlDictionaryReader          bodyReader = response.GetReaderAtBodyContents();

            using (bodyReader)
            {
                if (StandardsManager.MessageSecurityVersion.TrustVersion == TrustVersion.WSTrustFeb2005)
                {
                    rstr = StandardsManager.TrustDriver.CreateRequestSecurityTokenResponse(bodyReader);
                }
                else if (StandardsManager.MessageSecurityVersion.TrustVersion == TrustVersion.WSTrust13)
                {
                    RequestSecurityTokenResponseCollection rstrc = StandardsManager.TrustDriver.CreateRequestSecurityTokenResponseCollection(bodyReader);
                    foreach (RequestSecurityTokenResponse rstrItem in rstrc.RstrCollection)
                    {
                        if (rstr != null)
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.MoreThanOneRSTRInRSTRC));
                        }

                        rstr = rstrItem;
                    }
                }
                else
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
                }

                response.ReadFromBodyContentsToEnd(bodyReader);
            }

            byte[] requestorEntropy;
            if (requestState != null)
            {
                requestorEntropy = (byte[])requestState;
            }
            else
            {
                requestorEntropy = null;
            }

            GenericXmlSecurityToken issuedToken = rstr.GetIssuedToken(null, null, KeyEntropyMode, requestorEntropy, _sctUri, authorizationPolicies, SecurityAlgorithmSuite.DefaultSymmetricKeyLength, false);

            return(issuedToken);
        }
Example #24
0
 protected override void OnTokenAdded(IssuedTokenCacheBase.Key key, GenericXmlSecurityToken token)
 {
     using (FileStream fileStream = File.Open(this.fileName, FileMode.Append, FileAccess.Write))
     {
         fileStream.Seek(0L, SeekOrigin.End);
         FileIssuedTokenCache.SerializeCachedToken(fileStream, key.Target, key.Issuer, token);
     }
 }
Example #25
0
 protected override void OnTokenAdded(Key key, GenericXmlSecurityToken token)
 {
     using (FileStream str = File.Open(fileName, FileMode.Append, FileAccess.Write))
     {
         str.Seek(0, SeekOrigin.End);
         SerializeCachedToken(str, key.Target, key.Issuer, token);
     }
 }
Example #26
0
 protected override void OnTokenAdded(Key key, GenericXmlSecurityToken token)
 {
     using (FileStream str = File.Open(fileName, FileMode.Append, FileAccess.Write))
     {
         str.Seek(0, SeekOrigin.End);
         SerializeCachedToken(str, key.Target, key.Issuer, token);
     }
 }
 public void SetServiceToken(GenericXmlSecurityToken serviceToken)
 {
     if (this.IsNegotiationCompleted)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("NegotiationIsCompleted")));
     }
     this.serviceToken = serviceToken;
     this.isNegotiationCompleted = true;
 }
Example #28
0
        private string WrapInSoapMessage(GenericXmlSecurityToken token, string site)
        {
            var validFrom     = token.ValidFrom.ToString("o");
            var validTo       = token.ValidTo.ToString("o");
            var securityToken = token.TokenXml.OuterXml;
            var soapTemplate  = @"<t:RequestSecurityTokenResponse xmlns:t=""http://schemas.xmlsoap.org/ws/2005/02/trust""><t:Lifetime><wsu:Created xmlns:wsu=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"">{0}</wsu:Created><wsu:Expires xmlns:wsu=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"">{1}</wsu:Expires></t:Lifetime><wsp:AppliesTo xmlns:wsp=""http://schemas.xmlsoap.org/ws/2004/09/policy""><wsa:EndpointReference xmlns:wsa=""http://www.w3.org/2005/08/addressing""><wsa:Address>{2}</wsa:Address></wsa:EndpointReference></wsp:AppliesTo><t:RequestedSecurityToken>{3}</t:RequestedSecurityToken><t:TokenType>urn:oasis:names:tc:SAML:1.0:assertion</t:TokenType><t:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</t:RequestType><t:KeyType>http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey</t:KeyType></t:RequestSecurityTokenResponse>";

            return(string.Format(soapTemplate, validFrom, validTo, site, securityToken));
        }
 public void SetServiceToken(GenericXmlSecurityToken serviceToken)
 {
     if (this.IsNegotiationCompleted)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.NegotiationIsCompleted)));
     }
     this.serviceToken           = serviceToken;
     this.isNegotiationCompleted = true;
 }
Example #30
0
 public CompletedAsyncResult(GenericXmlSecurityToken token, AsyncCallback callback, object state)
 {
     this.token = token;
     this.state = state;
     if (callback != null)
     {
         callback(this);
     }
 }
        public static void tokenTest()
        {
            string relyingPartyId         = "https://shadfs.sanfordhealth.org/adfs/ls/ldpinitiatedsignon.aspx";
            WSTrustChannelFactory factory = null;

            try
            {
                // use a UserName Trust Binding for username authentication
                factory = new WSTrustChannelFactory(
                    new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                    new EndpointAddress("https://secure.genomenext.net/app/services/trust/13/usernamemixed"));
                /////I'll change this endpoint this later////////

                factory.TrustVersion = TrustVersion.WSTrust13;

                factory.Credentials.UserName.UserName = "******";
                factory.Credentials.UserName.Password = "******";

                var rst = new RequestSecurityToken
                {
                    RequestType = RequestTypes.Issue,
                    AppliesTo   = new EndpointReference(relyingPartyId),
                    KeyType     = KeyTypes.Bearer
                };
                IWSTrustChannelContract channel      = factory.CreateChannel();
                GenericXmlSecurityToken genericToken = channel.Issue(rst) as GenericXmlSecurityToken; //MessageSecurityException -> PW falsch

                var _handler    = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection();
                var tokenString = genericToken.ToTokenXmlString();

                var samlToken2 = _handler.ReadToken(new XmlTextReader(new StringReader(tokenString)));

                ValidateSamlToken(samlToken2);

                X509Certificate2 certificate = null;

                X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadOnly);
                certificate = store.Certificates.Find(X509FindType.FindByThumbprint, "thumb", false)[0];

                //  var jwt = ConvertSamlToJwt(samlToken2, "https://party.mycomp.com", certificate);
            }
            finally
            {
                if (factory != null)
                {
                    try
                    {
                        factory.Close();
                    }
                    catch (CommunicationObjectFaultedException)
                    {
                        factory.Abort();
                    }
                }
            }
Example #32
0
        protected override BodyWriter GetNextOutgoingMessageBody(Message incomingMessage, AcceleratedTokenProviderState negotiationState)
        {
            ReadOnlyCollection <IAuthorizationPolicy> authorizationPolicies;

            IssuanceTokenProviderBase <AcceleratedTokenProviderState> .ThrowIfFault(incomingMessage, base.TargetAddress);

            if (incomingMessage.Headers.Action != this.RequestSecurityTokenResponseAction.Value)
            {
                throw TraceUtility.ThrowHelperError(new SecurityNegotiationException(System.ServiceModel.SR.GetString("InvalidActionForNegotiationMessage", new object[] { incomingMessage.Headers.Action })), incomingMessage);
            }
            SecurityMessageProperty security = incomingMessage.Properties.Security;

            if ((security != null) && (security.ServiceSecurityContext != null))
            {
                authorizationPolicies = security.ServiceSecurityContext.AuthorizationPolicies;
            }
            else
            {
                authorizationPolicies = System.ServiceModel.Security.EmptyReadOnlyCollection <IAuthorizationPolicy> .Instance;
            }
            RequestSecurityTokenResponse response             = null;
            XmlDictionaryReader          readerAtBodyContents = incomingMessage.GetReaderAtBodyContents();

            using (readerAtBodyContents)
            {
                if (base.StandardsManager.MessageSecurityVersion.TrustVersion == TrustVersion.WSTrustFeb2005)
                {
                    response = RequestSecurityTokenResponse.CreateFrom(base.StandardsManager, readerAtBodyContents);
                }
                else
                {
                    if (base.StandardsManager.MessageSecurityVersion.TrustVersion != TrustVersion.WSTrust13)
                    {
                        throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
                    }
                    foreach (RequestSecurityTokenResponse response2 in base.StandardsManager.TrustDriver.CreateRequestSecurityTokenResponseCollection(readerAtBodyContents).RstrCollection)
                    {
                        if (response != null)
                        {
                            throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(System.ServiceModel.SR.GetString("MoreThanOneRSTRInRSTRC")));
                        }
                        response = response2;
                    }
                }
                incomingMessage.ReadFromBodyContentsToEnd(readerAtBodyContents);
            }
            if (response.Context != negotiationState.Context)
            {
                throw TraceUtility.ThrowHelperError(new SecurityNegotiationException(System.ServiceModel.SR.GetString("BadSecurityNegotiationContext")), incomingMessage);
            }
            byte[] requestorEntropy = negotiationState.GetRequestorEntropy();
            GenericXmlSecurityToken serviceToken = response.GetIssuedToken(null, null, this.keyEntropyMode, requestorEntropy, base.SecurityContextTokenUri, authorizationPolicies, base.SecurityAlgorithmSuite.DefaultSymmetricKeyLength, false);

            negotiationState.SetServiceToken(serviceToken);
            return(null);
        }
Example #33
0
        /// <summary>Turns a supported generic XML security token to a security token.</summary>
        /// <param name="token">The token.</param>
        /// <param name="decryptionCertificate">The decryption certificate.</param>
        /// <returns>A SecurityToken</returns>
        public static SecurityToken ToSecurityToken(this GenericXmlSecurityToken token, X509Certificate2 decryptionCertificate)
        {
            var configuration = new SecurityTokenHandlerConfiguration();

            configuration.ServiceTokenResolver = decryptionCertificate.CreateSecurityTokenResolver();

            var handler = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(configuration);

            return(token.ToSecurityToken(handler));
        }
        public GenericXmlSecurityToken GetIssuedToken(RequestSecurityToken rst)
        {
            EndpointAddress endpointAddress = new EndpointAddress(STSAddress, EndpointIdentity.CreateDnsIdentity(DnsIdentityForServiceCertificates));
            WSTrustClient   trustClient     = WSTrustClientFactory.GetWSTrustClient(clientCertifikat, serviceCertifikat, endpointAddress);

            GenericXmlSecurityToken token = (GenericXmlSecurityToken)trustClient.Issue(rst);

            trustClient.Close();
            return(token);
        }
        public void GetSaml2SecurityTokenFromJavaSTS()
        {
            SecurityToken bootstrapSecurityToken = BootstrapSecurityTokenGenerator.MakeBootstrapSecurityToken();

            RequestSecurityToken rst = WSTrustClientFactory.MakeOnBehalfOfSTSRequestSecurityToken(bootstrapSecurityToken, clientCertifikat, new Uri("http://localhost/Echo/service.svc/Echo"), requestClaims);

            GenericXmlSecurityToken token = GetIssuedToken(rst);

            Assert.IsTrue(token.InternalTokenReference.ToString().Contains("Saml2"));
        }
Example #36
0
		public NativeGenericXmlToken (GenericXmlSecurityToken token, SecurityTokenSerializer serializer)
		{
			created = token.ValidFrom.ToFileTime ();
			expired = token.ValidTo.ToFileTime ();
			xml_token = token.TokenXml.OuterXml;
			XmlWriterSettings settings = new XmlWriterSettings ();
			settings.OmitXmlDeclaration = true;
			internal_ref = GetKeyIdentifierClauseXml (serializer, settings, token.InternalTokenReference);
			external_ref = GetKeyIdentifierClauseXml (serializer, settings, token.ExternalTokenReference);
		}
Example #37
0
 protected override void ValidateKeySize(GenericXmlSecurityToken issuedToken)
 {
     if (this.keyType == SecurityKeyType.BearerKey)
     {
         // We do not have a proof key associated with bearer
         // key type. So skip key size validation.
         return;
     }
     base.ValidateKeySize(issuedToken);
 }
Example #38
0
 public override void AddToken(GenericXmlSecurityToken token, EndpointAddress target, EndpointAddress issuer)
 {
     if (token == null)
     {
         throw new ArgumentNullException("token");
     }
     if (target == null)
     {
         throw new ArgumentNullException("target");
     }
     lock (thisLock)
     {
         Key key = new Key(target.Uri, (issuer == null) ? null : issuer.Uri);
         this.cache.Add(key, token);
         OnTokenAdded(key, token);
     }
 }
        public ClaimsIdentity ValidateSamlToken(GenericXmlSecurityToken securityToken)
        {
            var _handler = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection();
            var tokenString = securityToken.ToTokenXmlString();

            var samlToken2 = _handler.ReadToken(new XmlTextReader(new StringReader(tokenString)));

            var configuration = new SecurityTokenHandlerConfiguration();
            configuration.AudienceRestriction.AudienceMode = AudienceUriMode.Never;
            configuration.CertificateValidationMode = X509CertificateValidationMode.None;
            configuration.RevocationMode = X509RevocationMode.NoCheck;
            configuration.CertificateValidator = X509CertificateValidator.None;

            var registry = new ConfigurationBasedIssuerNameRegistry();
            registry.AddTrustedIssuer(trustedIssuerCertificateThumbPrint, trustedIssuerName);
            configuration.IssuerNameRegistry = registry;

            var handler = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(configuration);
            var identity = handler.ValidateToken(samlToken2).First();
            return identity;
        }
        public TokenResponse ConvertToJwt(GenericXmlSecurityToken securityToken, string appliesToAddress, string issuerName, X509Certificate2 SigningCertificate)
        {
            var subject = this.tokenValidator.ValidateSamlToken(securityToken);

            var descriptor = new SecurityTokenDescriptor
            {
                Subject = subject,
                AppliesToAddress = appliesToAddress,
                SigningCredentials = new X509SigningCredentials(SigningCertificate),
                TokenIssuerName = issuerName,
                Lifetime = new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddMinutes(tokenLifeTimeMinutes))
            };

            var jwtHandler = new JwtSecurityTokenHandler();
            var jwt = jwtHandler.CreateToken(descriptor);

            return new TokenResponse
            {
                AccessToken = jwtHandler.WriteToken(jwt),
                ExpiresIn = tokenLifeTimeMinutes
            };
        }
 /// <summary>
 /// Requests an SWT Token using an input GenericXml SAML token.
 /// </summary>
 /// <param name="token">The input GenericXml SAML token.</param>
 /// <param name="scope">The requested scope.</param>
 /// <returns>The requested SWT token</returns>
 public SimpleWebToken Issue(GenericXmlSecurityToken token, Uri scope)
 {
     return IssueAssertion(token.TokenXml.OuterXml, "SAML", scope);
 }
        private HttpResponseMessage CreateTokenResponse(GenericXmlSecurityToken token, string scope)
        {
            var response = new TokenResponse();

            if (ConfigurationRepository.AdfsIntegration.PassThruAuthenticationToken)
            {
                response.AccessToken = token.TokenXml.OuterXml;
                response.ExpiresIn = (int)(token.ValidTo.Subtract(DateTime.UtcNow).TotalSeconds);
            }
            else
            {
                var bridge = new AdfsBridge(ConfigurationRepository);

                response = bridge.ConvertSamlToJwt(token.ToSecurityToken(), scope);
            }

            return Request.CreateResponse<TokenResponse>(HttpStatusCode.OK, response);
        }
        private HttpResponseMessage CreateTokenResponse(GenericXmlSecurityToken token, string scope)
        {
            var response = new TokenResponse();

            if (ConfigurationRepository.AdfsIntegration.PassThruAuthenticationToken)
            {
                response.AccessToken = token.TokenXml.OuterXml;
                response.ExpiresIn = (int)(token.ValidTo.Subtract(DateTime.UtcNow).TotalSeconds);
            }
            else
            {
                var bridge = new AdfsBridge(ConfigurationRepository);
                if (ConfigurationRepository.Keys.DecryptionCertificate != null)
                {
                    var configuration = new SecurityTokenHandlerConfiguration
                    {
                        AudienceRestriction = { AudienceMode = AudienceUriMode.Never },
                        CertificateValidationMode = X509CertificateValidationMode.None,
                        RevocationMode = X509RevocationMode.NoCheck,
                        CertificateValidator = X509CertificateValidator.None,
                        ServiceTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
                            new ReadOnlyCollection<SecurityToken>(new SecurityToken[] { new X509SecurityToken(ConfigurationRepository.Keys.DecryptionCertificate) }), false)
                    };
                    var handler = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(configuration);
                    response = bridge.ConvertSamlToJwt(token.ToSecurityToken(handler), scope);
                }
                else
                {
                    response = bridge.ConvertSamlToJwt(token.ToSecurityToken(), scope);
                }
            }

            return Request.CreateResponse<TokenResponse>(HttpStatusCode.OK, response);
        }
		public void WriteGenericXmlSecurityToken1 ()
		{
			StringWriter sw = new StringWriter ();

			XmlElement xml = new XmlDocument ().CreateElement ("foo");
			SecurityToken token = new X509SecurityToken (new X509Certificate2 ("Test/Resources/test.pfx", "mono"));
			SecurityKeyIdentifierClause intref =
				token.CreateKeyIdentifierClause<X509IssuerSerialKeyIdentifierClause> ();
			SecurityKeyIdentifierClause extref =
			null; //	token.CreateKeyIdentifierClause<X509IssuerSerialKeyIdentifierClause> ();
			ReadOnlyCollection<IAuthorizationPolicy> policies =
				new ReadOnlyCollection<IAuthorizationPolicy> (
					new IAuthorizationPolicy [0]);

			GenericXmlSecurityToken t = new GenericXmlSecurityToken (xml, token, DateTime.Now, new DateTime (2112, 9, 3), intref, extref, policies);
			using (XmlWriter w = XmlWriter.Create (sw, GetWriterSettings ())) {
				WSSecurityTokenSerializer.DefaultInstance.WriteToken (w, t);
			}
			// Huh?
			Assert.AreEqual ("<foo />", sw.ToString ());
		}
        private SecurityToken RequestFederationToken(GenericXmlSecurityToken xmlToken, string appliesTo)
        {
            var adfsEndpoint = this._configuration.AdfsIntegration.FederationEndpoint;

            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                AppliesTo = new EndpointReference(appliesTo),
                KeyType = KeyTypes.Bearer
            };

            var binding = new IssuedTokenWSTrustBinding();
            binding.SecurityMode = SecurityMode.TransportWithMessageCredential;

            var factory = new WSTrustChannelFactory(
                binding,
                new EndpointAddress(adfsEndpoint));
            factory.TrustVersion = TrustVersion.WSTrust13;
            factory.Credentials.SupportInteractive = false;

            var channel = factory.CreateChannelWithIssuedToken(xmlToken);
            return channel.Issue(rst);
        }
        // Summary
        //  Request a security token from the infocard system
        //
        // Parameters
        //  policyChain  - an array of PolicyElements that describe the federated security chain that the client
        //                 needs a final token to unwind.
        //
        public static GenericXmlSecurityToken GetToken(CardSpacePolicyElement[] policyChain, SecurityTokenSerializer tokenSerializer)
        {
            IDT.TraceDebug("ICARDCLIENT: GetToken called with a policy chain of length {0}", policyChain.Length);

            InfoCardProofToken proofToken = null;
            InternalRefCountedHandle nativeCryptoHandle = null;
            GenericXmlSecurityToken token = null;
            RpcGenericXmlToken infocardToken = new RpcGenericXmlToken();
            SafeTokenHandle nativeToken = null;
            Int32 result = 0;

            if (null == policyChain || 0 == policyChain.Length)
            {
                throw IDT.ThrowHelperArgumentNull("policyChain");
            }
            if (null == tokenSerializer)
            {
                throw IDT.ThrowHelperArgumentNull("tokenSerializer");
            }

            if (null == tokenSerializer)
            {
                throw IDT.ThrowHelperArgumentNull("tokenSerializer");
            }

            try
            {


                RuntimeHelpers.PrepareConstrainedRegions();
                bool mustRelease = false;
                try
                {
                }
                finally
                {
                    //
                    // The PolicyChain class will do the marshalling and native buffer management for us.
                    //
                    try
                    {
                        using (PolicyChain tmpChain = new PolicyChain(policyChain))
                        {

                            IDT.TraceDebug("ICARDCLIENT: PInvoking the native GetToken call");

                            result = GetShim().m_csShimGetToken(
                                                        tmpChain.Length,
                                                        tmpChain.DoMarshal(),
                                                        out nativeToken,
                                                        out nativeCryptoHandle);


                        }

                        if (0 == result)
                        {
                            IDT.TraceDebug("ICARDCLIENT: The PInvoke of GetToken succeeded");
                            nativeToken.DangerousAddRef(ref mustRelease);

                            infocardToken = (RpcGenericXmlToken)Marshal.PtrToStructure(
                                                                          nativeToken.DangerousGetHandle(),
                                                                          typeof(RpcGenericXmlToken));
                        }
                    }
                    finally
                    {
                        if (mustRelease)
                        {
                            nativeToken.DangerousRelease();
                        }
                    }

                }
                if (0 == result)
                {
                    using (ProofTokenCryptoHandle crypto =
                        (ProofTokenCryptoHandle)CryptoHandle.Create(nativeCryptoHandle))
                    {
                        proofToken = crypto.CreateProofToken();
                    }

                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.LoadXml(infocardToken.xmlToken);
                    SecurityKeyIdentifierClause internalTokenReference = null;
                    if (null != infocardToken.internalTokenReference)
                    {
                        internalTokenReference = tokenSerializer.ReadKeyIdentifierClause(
                                           CreateReaderWithQuotas(infocardToken.internalTokenReference));
                    }
                    SecurityKeyIdentifierClause externalTokenReference = null;
                    if (null != infocardToken.externalTokenReference)
                    {

                        externalTokenReference = tokenSerializer.ReadKeyIdentifierClause(
                                CreateReaderWithQuotas(infocardToken.externalTokenReference));
                    }
                    IDT.TraceDebug("ICARDCLIENT: Constructing a new GenericXmlSecurityToken");
                    token = new GenericXmlSecurityToken(
                                             xmlDoc.DocumentElement,
                                             proofToken,
                                             DateTime.FromFileTimeUtc(infocardToken.createDate),
                                             DateTime.FromFileTimeUtc(infocardToken.expiryDate),
                                             internalTokenReference,
                                             externalTokenReference,
                                             null);
                }
                else
                {
                    IDT.TraceDebug("ICARDCLIENT: The PInvoke of GetToken failed with a return code of {0}", result);

                    //
                    // Convert the HRESULTS to exceptions
                    //
                    ExceptionHelper.ThrowIfCardSpaceException((int)result);
                    throw IDT.ThrowHelperError(new CardSpaceException(SR.GetString(SR.ClientAPIInfocardError)));
                }
            }
            catch
            {
                if (null != nativeCryptoHandle)
                {
                    nativeCryptoHandle.Dispose();
                }

                if (null != proofToken)
                {
                    proofToken.Dispose();
                }
                throw;
            }
            finally
            {
                if (null != nativeToken)
                {
                    nativeToken.Dispose();
                }
            }

            return token;
        }
Example #47
0
 protected override void OnTokenAdded(Key key, GenericXmlSecurityToken token)
 {
 }
 public CompletedAsyncResult(GenericXmlSecurityToken token, AsyncCallback callback, object state)
 {
     this.token = token;
     this.state = state;
     if (callback != null)
     {
     //    this.callback = callback;
         callback(this);
     }
 }
Example #49
0
 protected abstract void OnTokenAdded(Key key, GenericXmlSecurityToken token);
Example #50
0
 public abstract bool TryGetToken(EndpointAddress target, EndpointAddress issuer, out GenericXmlSecurityToken cachedToken);
Example #51
0
 public abstract void AddToken(GenericXmlSecurityToken token, EndpointAddress target, EndpointAddress issuer);
Example #52
0
        static void PopulateCache(Dictionary<Key, GenericXmlSecurityToken> cache, Stream stream)
        {
            XmlTextReader reader = new XmlTextReader(stream);
            while (reader.IsStartElement("Entry"))
            {
                reader.ReadStartElement();
                Uri target = new Uri(reader.ReadElementString("Target"));
                string issuerStr = reader.ReadElementString("Issuer");
                Uri issuer = string.IsNullOrEmpty(issuerStr) ? null : new Uri(issuerStr);

                reader.ReadStartElement("Token");
                reader.ReadStartElement("XML");
                XmlDocument doc = new XmlDocument();
                XmlElement tokenXml = doc.ReadNode(reader) as XmlElement;
                reader.ReadEndElement();
                byte[] key = Convert.FromBase64String(reader.ReadElementString("Key"));
                reader.ReadElementString("Id");
                DateTime validFrom = Convert.ToDateTime(reader.ReadElementString("ValidFrom"));
                DateTime validTo = Convert.ToDateTime(reader.ReadElementString("ValidTo"));
                WSSecurityTokenSerializer serializer = new WSSecurityTokenSerializer();
                reader.ReadStartElement("InternalTokenReference");
                SecurityKeyIdentifierClause internalReference = serializer.ReadKeyIdentifierClause(reader);
                reader.ReadEndElement();
                reader.ReadStartElement("ExternalTokenReference");
                SecurityKeyIdentifierClause externalReference = serializer.ReadKeyIdentifierClause(reader);
                reader.ReadEndElement();
                reader.ReadEndElement(); // token
                reader.ReadEndElement(); // entry

                List<IAuthorizationPolicy> policies = new List<IAuthorizationPolicy>();
                GenericXmlSecurityToken token = new GenericXmlSecurityToken(tokenXml, new BinarySecretSecurityToken(key), validFrom, validTo, internalReference, externalReference,
                    new ReadOnlyCollection<IAuthorizationPolicy>(policies));
                cache.Add(new Key(target, issuer), token);
            }
        }
Example #53
0
        // Since the issued token is an endorsing token it will not be used for identity checks
        // hence we do not need to persist the authorization policies that represent the target service.
        static void SerializeCachedToken(Stream stream, Uri target, Uri issuer, GenericXmlSecurityToken token)
        {
            XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8);
            writer.WriteStartElement("Entry");
            writer.WriteElementString("Target", target.AbsoluteUri);
            writer.WriteElementString("Issuer", (issuer == null) ? "" : issuer.AbsoluteUri);

            writer.WriteStartElement("Token");
            writer.WriteStartElement("XML");
            token.TokenXml.WriteTo(writer);
            writer.WriteEndElement();
            SymmetricSecurityKey key = (SymmetricSecurityKey)(token.SecurityKeys[0]);
            writer.WriteElementString("Key", Convert.ToBase64String(key.GetSymmetricKey()));
            writer.WriteElementString("Id", token.Id);
            writer.WriteElementString("ValidFrom", Convert.ToString(token.ValidFrom));
            writer.WriteElementString("ValidTo", Convert.ToString(token.ValidTo));
            WSSecurityTokenSerializer serializer = new WSSecurityTokenSerializer();
            writer.WriteStartElement("InternalTokenReference");
            serializer.WriteKeyIdentifierClause(writer, token.InternalTokenReference);
            writer.WriteEndElement();
            writer.WriteStartElement("ExternalTokenReference");
            serializer.WriteKeyIdentifierClause(writer, token.ExternalTokenReference);
            writer.WriteEndElement();

            writer.WriteEndElement(); // token
            writer.WriteEndElement(); // entry

            writer.Flush();
            stream.Flush();
        }