Esempio n. 1
0
        /// <summary>
        /// Makes a WSTrust call to the STS to obtain a <see cref="SecurityToken"/> first checking if the token is available in the cache.
        /// </summary>
        /// <returns>A <see cref="GenericXmlSecurityToken"/>.</returns>
        protected override SecurityToken GetTokenCore(TimeSpan timeout)
        {
            _communicationObject.ThrowIfClosedOrNotOpen();
            WsTrustRequest  request       = CreateWsTrustRequest();
            WsTrustResponse trustResponse = GetCachedResponse(request);

            if (trustResponse is null)
            {
                using (var memeoryStream = new MemoryStream())
                {
                    var writer     = XmlDictionaryWriter.CreateTextWriter(memeoryStream, Encoding.UTF8);
                    var serializer = new WsTrustSerializer();
                    serializer.WriteRequest(writer, _requestSerializationContext.TrustVersion, request);
                    writer.Flush();
                    var             reader  = XmlDictionaryReader.CreateTextReader(memeoryStream.ToArray(), XmlDictionaryReaderQuotas.Max);
                    IRequestChannel channel = ChannelFactory.CreateChannel();
                    try
                    {
                        channel.Open();
                        Message reply = channel.Request(Message.CreateMessage(MessageVersion.Soap12WSAddressing10, _requestSerializationContext.TrustActions.IssueRequest, reader));
                        SecurityUtils.ThrowIfNegotiationFault(reply, channel.RemoteAddress);
                        trustResponse = serializer.ReadResponse(reply.GetReaderAtBodyContents());
                        CacheSecurityTokenResponse(request, trustResponse);
                    }
                    finally
                    {
                        channel.Close();
                    }
                }
            }

            return(WSTrustUtilities.CreateGenericXmlSecurityToken(request, trustResponse, _requestSerializationContext, _securityAlgorithmSuite));
        }
 public WsTrustRequestBodyWriter(WsTrustVersion version, WsTrustSerializer serializer, WsTrustRequest request)
     : base(true)
 {
     _version    = version;
     _request    = request;
     _serializer = serializer;
 }
Esempio n. 3
0
        public WsFedMiddleware(RequestDelegate next,
                               ILogger <WsFedMiddleware> logger,
                               IRelyingPartyStore relyingPartyStore,
                               SignInResponseGenerator responseGenerator,
                               WsTrustSerializer serializer,
                               IOptions <FederationGatewayOptions> options)
        {
            if (next == null)
            {
                throw new ArgumentNullException(nameof(next));
            }
            if (relyingPartyStore == null)
            {
                throw new ArgumentNullException(nameof(relyingPartyStore));
            }
            if (responseGenerator == null)
            {
                throw new ArgumentNullException(nameof(responseGenerator));
            }
            if (serializer == null)
            {
                throw new ArgumentNullException(nameof(serializer));
            }
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            _next              = next;
            _logger            = logger;
            _relyingPartyStore = relyingPartyStore;
            _responseGenerator = responseGenerator;
            _serializer        = serializer;
            _options           = options.Value;
        }
        /// <summary>
        /// Makes a WSTrust call to the STS to obtain a <see cref="SecurityToken"/> first checking if the token is available in the cache.
        /// </summary>
        /// <returns>A <see cref="GenericXmlSecurityToken"/>.</returns>
        protected override SecurityToken GetTokenCore(TimeSpan timeout)
        {
            WsTrustRequest  request       = CreateWsTrustRequest();
            WsTrustResponse trustResponse = GetCachedResponse(request);

            if (trustResponse is null)
            {
                using (var memeoryStream = new MemoryStream())
                {
                    var writer     = XmlDictionaryWriter.CreateTextWriter(memeoryStream, Encoding.UTF8);
                    var serializer = new WsTrustSerializer();
                    serializer.WriteRequest(writer, _requestSerializationContext.TrustVersion, request);
                    writer.Flush();
                    var             reader  = XmlDictionaryReader.CreateTextReader(memeoryStream.ToArray(), XmlDictionaryReaderQuotas.Max);
                    IRequestChannel channel = ChannelFactory.CreateChannel();
                    Message         reply   = channel.Request(Message.CreateMessage(MessageVersion.Soap12WSAddressing10, _requestSerializationContext.TrustActions.IssueRequest, reader));
                    SecurityUtils.ThrowIfNegotiationFault(reply, channel.RemoteAddress);
                    trustResponse = serializer.ReadResponse(reply.GetReaderAtBodyContents());
                    CacheSecurityTokenResponse(request, trustResponse);
                }
            }

            // Create GenericXmlSecurityToken
            // Assumes that token is first and Saml2SecurityToken.
            using (var stream = new MemoryStream())
            {
                RequestSecurityTokenResponse response = trustResponse.RequestSecurityTokenResponseCollection[0];

                // Get attached and unattached references
                GenericXmlSecurityKeyIdentifierClause internalSecurityKeyIdentifierClause = null;
                if (response.AttachedReference != null)
                {
                    internalSecurityKeyIdentifierClause = GetSecurityKeyIdentifierForTokenReference(response.AttachedReference);
                }

                GenericXmlSecurityKeyIdentifierClause externalSecurityKeyIdentifierClause = null;
                if (response.UnattachedReference != null)
                {
                    externalSecurityKeyIdentifierClause = GetSecurityKeyIdentifierForTokenReference(response.UnattachedReference);
                }

                // Get proof token
                IdentityModel.Tokens.SecurityToken proofToken = GetProofToken(request, response);

                // Get lifetime
                DateTime created = response.Lifetime?.Created ?? DateTime.UtcNow;
                DateTime expires = response.Lifetime?.Expires ?? created.AddDays(1);

                return(new GenericXmlSecurityToken(response.RequestedSecurityToken.TokenElement,
                                                   proofToken,
                                                   created,
                                                   expires,
                                                   internalSecurityKeyIdentifierClause,
                                                   externalSecurityKeyIdentifierClause,
                                                   null));
            }
        }
        /// <summary>
        /// Creates a channel.
        /// </summary>
        /// <param name="address">The <see cref="EndpointAddress"/> that provides the location of the service.</param>
        /// <param name="via">The <see cref="Uri"/> that contains the transport address to which the channel sends messages.</param>
        /// <returns>A channel of type <see cref="IWsTrustChannelContract"/>.</returns>
        public override IWsTrustChannelContract CreateChannel(EndpointAddress address, Uri via)
        {
            var channel    = base.CreateChannel(address, via);
            var serializer = new WsTrustSerializer();

            serializer.SecurityTokenHandlers.Clear();
            foreach (var handler in GetSupportedSecurityTokenHandlers())
            {
                serializer.SecurityTokenHandlers.Add(handler);
            }
            return(new WsTrustChannel(TrustVersion, channel, serializer));
        }
        public WsTrustChannel(WsTrustVersion version, IWsTrustContract contract, WsTrustSerializer serializer)
            : base(contract as IChannel)
        {
            // TODO: add null guards
            _version   = version;
            _constants = GetConstants(version);
            // TODO: get message version from binding
            _messageVersion = MessageVersion.Default;
            _contract       = contract;

            _serializer = serializer;
        }
Esempio n. 7
0
        public WsTrustSerializer Create()
        {
            var serializer = new WsTrustSerializer();

            serializer.SecurityTokenHandlers.Clear();
            var handlers = SecurityTokenHandlerProvider.GetAllSecurityTokenHandlers();

            foreach (var handler in handlers)
            {
                serializer.SecurityTokenHandlers.Add(handler);
            }
            return(serializer);
        }
        private void WriteSecurityTokenReference(XmlDictionaryWriter writer, SecurityTokenReference reference, bool attached)
        {
            var context = new WsSerializationContext(_version);

            if (attached)
            {
                WsTrustSerializer.WriteRequestedAttachedReference(writer, context, reference);
            }
            else
            {
                WsTrustSerializer.WriteRequestedUnattachedReference(writer, context, reference);
            }
        }
Esempio n. 9
0
        public async Task ShouldSerializeToken()
        {
            var responseGenerator = new SignInResponseGenerator(_logger,
                                                                _relyingPartyStore,
                                                                _profileManager,
                                                                _keyManager,
                                                                _options
                                                                );

            var response = await responseGenerator.GenerateSignInResponse(new SignInRequest
            {
                Realm = "urn:test",
                User  = new ClaimsPrincipal(new List <ClaimsIdentity>
                {
                    new ClaimsIdentity(new List <Claim>
                    {
                        new Claim(ClaimTypes.NameIdentifier, "john foo")
                    })
                }),
                Parameters = new Dictionary <string, string>()
                {
                }
            });

            var sb        = new StringBuilder();
            var xmlWriter = XmlWriter.Create(new StringWriter(sb), new XmlWriterSettings {
                Encoding = Encoding.UTF8
            });
            var serializer = new WsTrustSerializer();

            var wsTrust = new WsTrustRequestSecurityTokenResponse();

            wsTrust.LifeTime = new WsTrustLifetime
            {
                Expires = DateTime.Now.AddHours(8),
                Created = DateTime.Now
            };
            wsTrust.AppliesTo = new Uri("urn:test");
            wsTrust.RequestedSecurityToken = (Saml2SecurityToken)response.Token;

            serializer.Serialize(xmlWriter, wsTrust);

            xmlWriter.Flush();

            Assert.True(sb.ToString().Length > 0);
        }
        private async Task <SecurityToken> GetTokenAsyncCore(TimeSpan timeout)
        {
            _communicationObject.ThrowIfClosedOrNotOpen();
            WsTrustRequest  request       = CreateWsTrustRequest();
            WsTrustResponse trustResponse = GetCachedResponse(request);

            if (trustResponse is null)
            {
                using (var memeoryStream = new MemoryStream())
                {
                    var writer     = XmlDictionaryWriter.CreateTextWriter(memeoryStream, Encoding.UTF8);
                    var serializer = new WsTrustSerializer();
                    serializer.WriteRequest(writer, _requestSerializationContext.TrustVersion, request);
                    writer.Flush();
                    var             reader  = XmlDictionaryReader.CreateTextReader(memeoryStream.ToArray(), XmlDictionaryReaderQuotas.Max);
                    IRequestChannel channel = ChannelFactory.CreateChannel();
                    await Task.Factory.FromAsync(channel.BeginOpen, channel.EndOpen, null, TaskCreationOptions.None);

                    try
                    {
                        Message requestMessage = Message.CreateMessage(MessageVersion.Soap12WSAddressing10, _requestSerializationContext.TrustActions.IssueRequest, reader);
                        Message reply          = await Task.Factory.FromAsync(channel.BeginRequest, channel.EndRequest, requestMessage, null, TaskCreationOptions.None);

                        SecurityUtils.ThrowIfNegotiationFault(reply, channel.RemoteAddress);
                        trustResponse = serializer.ReadResponse(reply.GetReaderAtBodyContents());
                        CacheSecurityTokenResponse(request, trustResponse);
                    }
                    finally
                    {
                        await Task.Factory.FromAsync(channel.BeginClose, channel.EndClose, null, TaskCreationOptions.None);
                    }
                }
            }

            return(CreateGenericXmlSecurityToken(request, trustResponse));
        }
Esempio n. 11
0
        //public override KeyInfo ReadKeyInfo(XmlReader reader)
        //{
        //    const string xmlenc = "http://www.w3.org/2001/04/xmlenc#";

        //    // buffer element
        //    var document = XDocument.Load(reader.ReadSubtree());
        //    var keyInfo = document.Root;
        //    var child = keyInfo.Nodes().OfType<XElement>().FirstOrDefault();
        //    reader.Read();

        //    if (child != null)
        //    {
        //        if (child.Name == XName.Get("EncryptedKey", xmlenc))
        //        {

        //        }

        //        if (child.Name == XName.Get("BinarySecret", WsTrustConstants.TrustFeb2005.Namespace) ||
        //            child.Name == XName.Get("BinarySecret", WsTrustConstants.Trust13.Namespace) ||
        //            child.Name == XName.Get("BinarySecret", WsTrustConstants.Trust14.Namespace))
        //        {
        //            var base64 = child.Value;
        //            var key = Convert.FromBase64String(base64);

        //            return new BinarySecretKeyInfo
        //            {
        //                Key = key
        //            };
        //        }

        //        if (child.Name == XName.Get("SecurityTokenReference", WsSecurityConstants.WsSecurity10.Namespace))
        //        {
        //            var keyIdentifier = child.Nodes().OfType<XElement>().FirstOrDefault(e => e.Name == XName.Get("KeyIdentifier", WsSecurityConstants.WsSecurity10.Namespace));
        //            var valueType = keyIdentifier?.Attribute(XName.Get("ValueType", string.Empty));
        //            var id = keyIdentifier?.Value;

        //            return new SecurityTokenReferenceKeyInfo
        //            {
        //                KeyIdValueType = valueType?.Value,
        //                KeyId = id
        //            };
        //        }
        //    }

        //    using (var temp = document.CreateReader())
        //    {
        //        temp.Settings.IgnoreWhitespace = true;
        //        temp.Read();
        //        return base.ReadKeyInfo(temp);
        //    }
        //}

        public override void WriteKeyInfo(XmlWriter writer, KeyInfo keyInfo)
        {
            if (keyInfo is EncryptedKeyInfo encrypted)
            {
                const string xmlenc = "http://www.w3.org/2001/04/xmlenc#";

                // <KeyInfo>
                writer.WriteStartElement(XmlSignatureConstants.Elements.KeyInfo, XmlSignatureConstants.Namespace);
                writer.WriteStartElement("EncryptedKey", xmlenc);

                writer.WriteStartElement("EncryptionMethod", xmlenc);
                writer.WriteAttributeString("Algorithm", encrypted.EncryptionMethod);
                if (!string.IsNullOrEmpty(encrypted.DigestMethod))
                {
                    writer.WriteStartElement("DigestMethod", XmlSignatureConstants.Namespace);
                    writer.WriteAttributeString("Algorithm", encrypted.DigestMethod);
                    writer.WriteEndElement();
                }
                writer.WriteEndElement();

                WriteKeyInfo(writer, encrypted.KeyInfo);

                writer.WriteStartElement("CipherData", xmlenc);
                writer.WriteStartElement("CipherValue", xmlenc);
                writer.WriteString(Convert.ToBase64String(encrypted.CipherValue));
                writer.WriteEndElement();
                writer.WriteEndElement();

                writer.WriteEndElement();
                writer.WriteEndElement();
                return;
            }

            if (keyInfo is BinarySecretKeyInfo binary)
            {
                // <KeyInfo>
                writer.WriteStartElement(XmlSignatureConstants.Elements.KeyInfo, XmlSignatureConstants.Namespace);
                var binarySecret        = new BinarySecret(binary.Key);
                var xmlDictionaryWriter = XmlDictionaryWriter.CreateDictionaryWriter(writer);
                var version             = null as WsTrustVersion;
                if (xmlDictionaryWriter.LookupPrefix(WsTrustConstants.TrustFeb2005.Namespace) != null)
                {
                    version = WsTrustVersion.TrustFeb2005;
                }
                else if (xmlDictionaryWriter.LookupPrefix(WsTrustConstants.Trust14.Namespace) != null)
                {
                    version = WsTrustVersion.Trust14;
                }
                else
                {
                    version = WsTrustVersion.Trust13; // default to Trust 1.3
                }
                WsTrustSerializer.WriteBinarySecret(xmlDictionaryWriter, new WsSerializationContext(version), binarySecret);
                writer.WriteEndElement();
                return;
            }

            // this might be a bit naive
            if (keyInfo is SecurityTokenReferenceKeyInfo securityTokenReference)
            {
                // <KeyInfo>
                writer.WriteStartElement(XmlSignatureConstants.Elements.KeyInfo, XmlSignatureConstants.Namespace);
                writer.WriteStartElement(WsSecurityConstants.WsSecurity10.Prefix, "SecurityTokenReference", WsSecurityConstants.WsSecurity10.Namespace);
                writer.WriteStartElement(WsSecurityConstants.WsSecurity10.Prefix, "KeyIdentifier", WsSecurityConstants.WsSecurity10.Namespace);
                writer.WriteAttributeString("ValueType", securityTokenReference.KeyIdValueType);

                writer.WriteString(securityTokenReference.KeyId);

                writer.WriteEndElement();
                writer.WriteEndElement();
                writer.WriteEndElement();
                return;
            }

            base.WriteKeyInfo(writer, keyInfo);
        }
 public WsTrustResponseObjectSerializer(WsTrustVersion version, WsTrustSerializer inner)
 {
     _version = version;
     _inner   = inner;
 }
Esempio n. 13
0
 /// <summary>
 /// Constructor for the WSTrustRequestBodyWriter.
 /// </summary>
 /// <param name="trustRequest">The <see cref="WsTrustRequest"/> to be serialized in a outgoing Message.</param>
 /// <param name="trustSerializer">The <see cref="WsTrustSerializer"/> used to write the <see cref="WsTrustRequest"/> into a <see cref="XmlDictionaryWriter"/>.</param>
 public WSTrustRequestBodyWriter(WsTrustRequest trustRequest, WsTrustSerializer trustSerializer) : base(true)
 {
     TrustRequest    = trustRequest ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(trustRequest));
     TrustSerializer = trustSerializer ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(trustSerializer));
 }