public async Task<SignInResponseMessage> GenerateResponseAsync(SignInValidationResult validationResult)
        {
            Logger.Info("Creating WS-Federation signin response");

            // create subject
            var outgoingSubject = await CreateSubjectAsync(validationResult);

            // create token for user
            var token = CreateSecurityToken(validationResult, outgoingSubject);

            // return response
            var rstr = new RequestSecurityTokenResponse
            {
                AppliesTo = new EndpointReference(validationResult.RelyingParty.Realm),
                Context = validationResult.SignInRequestMessage.Context,
                ReplyTo = validationResult.ReplyUrl,
                RequestedSecurityToken = new RequestedSecurityToken(token)
            };

            var serializer = new WSFederationSerializer(
                new WSTrust13RequestSerializer(),
                new WSTrust13ResponseSerializer());

            var responseMessage = new SignInResponseMessage(
                new Uri(validationResult.ReplyUrl),
                rstr,
                serializer,
                new WSTrustSerializationContext());

            return responseMessage;
        }
Example #2
0
        /// <summary>
        /// Sets the appropriate things, such as requested proof token, inside the RSTR
        /// based on what is inside the proof descriptor instance.
        /// </summary>
        /// <param name="response">The RSTR object that this proof descriptor needs to modify.</param>
        /// <exception cref="ArgumentNullException">When the response is null.</exception>
        public override void ApplyTo(RSTR response)
        {
            if (response == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("response");
            }

            if (_targetEntropy != null)
            {
                //
                // When there is target entropy, then we will send back a computedKeyalgorithm
                // in the proof token case and send the entropy as response.Entropy. By default, this
                // class is doing Psha1.
                //
                response.RequestedProofToken = new RequestedProofToken(ComputedKeyAlgorithms.Psha1);
                response.KeySizeInBits       = _keySizeInBits;
                response.Entropy             = new Entropy(_targetEntropy, _requestorWrappingCredentials);
            }
            else
            {
                //
                // When there is no target entroypy, then we will send back the key either in
                // binary secret format or in the encrypted key format
                //
                response.RequestedProofToken = new RequestedProofToken(_key, _requestorWrappingCredentials);
            }
        }
        public SignInResponseMessage Generate(SignInRequestMessage request, WindowsPrincipal windowsPrincipal)
        {
            Logger.Info("Creating WS-Federation signin response");

            // create subject
            var outgoingSubject = SubjectGenerator.Create(windowsPrincipal, _options);

            // create token for user
            var token = CreateSecurityToken(outgoingSubject);

            // return response
            var rstr = new RequestSecurityTokenResponse
            {
                AppliesTo = new EndpointReference(_options.IdpRealm),
                Context = request.Context,
                ReplyTo = _options.IdpReplyUrl,
                RequestedSecurityToken = new RequestedSecurityToken(token)
            };

            var serializer = new WSFederationSerializer(
                new WSTrust13RequestSerializer(),
                new WSTrust13ResponseSerializer());

            var mgr = SecurityTokenHandlerCollectionManager.CreateEmptySecurityTokenHandlerCollectionManager();
            mgr[SecurityTokenHandlerCollectionManager.Usage.Default] = CreateSupportedSecurityTokenHandler();

            var responseMessage = new SignInResponseMessage(
                new Uri(_options.IdpReplyUrl),
                rstr,
                serializer,
                new WSTrustSerializationContext(mgr));

            return responseMessage;
        }
        /// <summary>
        /// Serializes a RequestSecurityTokenResponse object to the given XmlWriter
        /// stream.
        /// </summary>
        /// <param name="response">RequestSecurityTokenResponse object that needs to be serialized to the writer.</param>
        /// <param name="writer">XmlWriter into which the object will be serialized</param>
        /// <param name="context">Current Serialization context.</param>
        /// <exception cref="ArgumentNullException">The given response or writer or context parameter is null</exception>
        public override void WriteXml(RequestSecurityTokenResponse response, XmlWriter writer, WSTrustSerializationContext context)
        {
            if (response == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("response");
            }

            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

            if (context == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
            }

            if (response.IsFinal)
            {
                writer.WriteStartElement(WSTrust13Constants.Prefix, WSTrust13Constants.ElementNames.RequestSecurityTokenResponseCollection, WSTrust13Constants.NamespaceURI);
            }

            WSTrustSerializationHelper.WriteResponse(response, writer, context, this, WSTrustConstantsAdapter.Trust13);

            if (response.IsFinal)
            {
                writer.WriteEndElement();
            }
        }
        /// <summary>
        /// Deserializes an RSTR and returns a RequestSecurityTokenRespone object.
        /// </summary>
        /// <param name="reader">Reader over the RSTR.</param>
        /// <param name="context">Current Serialization context.</param>
        /// <returns>RequestSecurityTokenResponse object if deserialization was successful.</returns>
        /// <exception cref="ArgumentNullException">The given reader or context parameter is null</exception>
        public override RequestSecurityTokenResponse ReadXml(XmlReader reader, WSTrustSerializationContext context)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            if (context == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
            }

            bool isFinal = false;

            if (reader.IsStartElement(WSTrust13Constants.ElementNames.RequestSecurityTokenResponseCollection, WSTrust13Constants.NamespaceURI))
            {
                reader.ReadStartElement(WSTrust13Constants.ElementNames.RequestSecurityTokenResponseCollection, WSTrust13Constants.NamespaceURI);
                isFinal = true;
            }

            RequestSecurityTokenResponse rstr = WSTrustSerializationHelper.CreateResponse(reader, context, this, WSTrustConstantsAdapter.Trust13);

            rstr.IsFinal = isFinal;

            if (isFinal)
            {
                reader.ReadEndElement();
            }

            return(rstr);
        }
        /// <summary>
        /// Override of the base class that Reads a specific child element inside the RSTR.
        /// </summary>
        /// <param name="reader">Reader pointing at an element to read inside the RSTR.</param>
        /// <param name="rstr">The RequestSecurityTokenResponse element that is being populated from the reader.</param>
        /// <param name="context">Current Serialization context.</param>
        /// <exception cref="ArgumentNullException">Either reader or rstr or context parameter is null.</exception>
        /// <exception cref="WSTrustSerializationException">Unable to deserialize the current parameter.</exception>
        public override void ReadXmlElement(XmlReader reader, RequestSecurityTokenResponse rstr, WSTrustSerializationContext context)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            if (rstr == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rstr");
            }

            if (context == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
            }

            if (reader.IsStartElement(WSTrust13Constants.ElementNames.KeyWrapAlgorithm, WSTrust13Constants.NamespaceURI))
            {
                rstr.KeyWrapAlgorithm = reader.ReadElementContentAsString();
                return;
            }

            WSTrustSerializationHelper.ReadRSTRXml(reader, rstr, context, WSTrustConstantsAdapter.Trust13);
        }
        /// <summary>
        /// Writes out the supported elements on the response object.
        /// </summary>
        /// <param name="rstr">The response instance</param>
        /// <param name="writer">The writer to write to</param>
        /// <param name="context">Current Serialization context.</param>
        /// <exception cref="ArgumentNullException">Either rstr or writer or context parameter is null.</exception>
        public override void WriteKnownResponseElement(RequestSecurityTokenResponse rstr, XmlWriter writer, WSTrustSerializationContext context)
        {
            if (rstr == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rstr");
            }

            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

            if (context == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
            }

            // Write out the exisiting ones
            WSTrustSerializationHelper.WriteKnownResponseElement(rstr, writer, context, this, WSTrustConstantsAdapter.Trust13);

            // Specific to WS-Trust 13
            if (!string.IsNullOrEmpty(rstr.KeyWrapAlgorithm))
            {
                this.WriteXmlElement(writer, WSTrust13Constants.ElementNames.KeyWrapAlgorithm, rstr.KeyWrapAlgorithm, rstr, context);
            }
        }
        /// <summary>
        /// Override of the base class that Reads a specific child element inside the RSTR.
        /// </summary>
        /// <param name="reader">Reader pointing at an element to read inside the RSTR.</param>
        /// <param name="rstr">The RequestSecurityTokenResponse element that is being populated from the reader.</param>
        /// <param name="context">Current Serialization context.</param>
        /// <exception cref="ArgumentNullException">Either reader or rstr or context parameter is null.</exception>
        /// <exception cref="WSTrustSerializationException">Unable to deserialize the current parameter.</exception>
        public override void ReadXmlElement(XmlReader reader, RequestSecurityTokenResponse rstr, WSTrustSerializationContext context)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            if (rstr == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rstr");
            }

            if (context == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
            }

            if (reader.IsStartElement(WSTrust13Constants.ElementNames.KeyWrapAlgorithm, WSTrust13Constants.NamespaceURI))
            {
                rstr.KeyWrapAlgorithm = reader.ReadElementContentAsString();
                return;
            }

            WSTrustSerializationHelper.ReadRSTRXml(reader, rstr, context, WSTrustConstantsAdapter.Trust13);
        }
 /// <summary>
 /// Validates the RequestSecurityTokenResponse object that has been deserialized.
 /// </summary>
 /// <param name="requestSecurityTokenResponse">The RequestSecurityTokenResponse object to Validate.</param>
 /// <exception cref="InvalidOperationException">An Response for an IssueRequest does not contain the RequestedSecurityToken.</exception>
 public virtual void Validate(RequestSecurityTokenResponse requestSecurityTokenResponse)
 {
     if (requestSecurityTokenResponse == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rstr");
     }
 }
 /// <summary>
 /// Validates the RequestSecurityTokenResponse object that has been deserialized.
 /// </summary>
 /// <param name="requestSecurityTokenResponse">The RequestSecurityTokenResponse object to Validate.</param>
 /// <exception cref="InvalidOperationException">An Response for an IssueRequest does not contain the RequestedSecurityToken.</exception>
 public virtual void Validate(RequestSecurityTokenResponse requestSecurityTokenResponse)
 {
     if (requestSecurityTokenResponse == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rstr");
     }
 }
        /// <summary>
        /// Requests a token desribed by an RST.
        /// </summary>
        /// <param name="stsAddress">The STS address.</param>
        /// <param name="binding">The binding.</param>
        /// <param name="credentials">The credentials.</param>
        /// <param name="rst">The RST.</param>
        /// <param name="rstr">The RSTR.</param>
        /// <returns>A SecurityToken</returns>
        public static SecurityToken Issue(EndpointAddress stsAddress, Binding binding, ClientCredentials credentials, RequestSecurityToken rst, out RequestSecurityTokenResponse rstr)
        {
            var channel = CreateWSTrustChannel(
                stsAddress,
                binding,
                credentials);

            var token = channel.Issue(rst, out rstr);
            return token;
        }
        private static SecurityToken IssueTokenWithUserNamePassword(string username, string password, string issuerUri, string appliesTo, out RequestSecurityTokenResponse RSTR, string keyType = KeyTypes.Bearer)
        {
            if (String.IsNullOrWhiteSpace(issuerUri)) throw new ArgumentNullException("issuerUri");
            if (String.IsNullOrWhiteSpace(appliesTo)) throw new ArgumentNullException("appliesTo");

            Binding binding = null;
            var WsHttpBinding = new WS2007HttpBinding(SecurityMode.TransportWithMessageCredential);

            // Avoid the WS-SecureConversation piece
            WsHttpBinding.Security.Message.EstablishSecurityContext = false;
            WsHttpBinding.Security.Message.NegotiateServiceCredential = false;
            WsHttpBinding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;

            // Set our binding variable
            binding = WsHttpBinding;

            // Define the STS endpoint
            EndpointAddress endpoint = new EndpointAddress(new Uri(issuerUri));

            var factory = new WSTrustChannelFactory(binding, endpoint) { TrustVersion = TrustVersion.WSTrust13 };

            // Here is where we set the credentials (goes into the SOAP security header)
            factory.Credentials.SupportInteractive = false; // Avoid that CardSpace popup...
            factory.Credentials.UserName.UserName = username;
            factory.Credentials.UserName.Password = password;

            SecurityTokenElement OnBehalfOfElement = new SecurityTokenElement(new UserNameSecurityToken("pbell", "2Federate"));
            SecurityTokenElement ActAsElement = new SecurityTokenElement(new UserNameSecurityToken("mpavlich", "2Federate"));

            // Now we define the Request for Security Token (RST)
            RequestSecurityToken RST = new RequestSecurityToken()
            {
                //identifiy who this token is for
                AppliesTo = new EndpointReference(appliesTo),
                //identify what type of request this is (Issue or Validate)
                RequestType = RequestTypes.Issue,
                //set the keytype (symmetric, asymmetric (pub key) or bearer)
                KeyType = keyType
            };

            // Create the WS-Trust channel
            IWSTrustChannelContract channel = factory.CreateChannel();

            // Send the Issue RST request
            SecurityToken token = channel.Issue(RST, out RSTR);

            return token;
        }
        public string Serialize(RequestSecurityTokenResponse securityTokenResponse)
        {
            XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
            xmlWriterSettings.OmitXmlDeclaration = true;

            using (MemoryStream memoryStream = new MemoryStream())
            using (XmlWriter xmlWriter = XmlWriter.Create(memoryStream, xmlWriterSettings))
            {
                WSTrust13ResponseSerializer serializer = new WSTrust13ResponseSerializer();
                WSTrustSerializationContext context = new WSTrustSerializationContext();
                serializer.WriteXml(securityTokenResponse, xmlWriter, context);
                xmlWriter.Flush();
                var encoding = new System.Text.UTF8Encoding(false);
                return encoding.GetString(memoryStream.ToArray());

            }
        }
Example #14
0
        /// <summary>
        /// Writes out the supported elements on the response object.
        /// </summary>
        /// <param name="rstr">The response instance</param>
        /// <param name="writer">The writer to write to</param>
        /// <param name="context">Current Serialization context.</param>
        /// <exception cref="ArgumentNullException">Either rstr or writer or context parameter is null.</exception>
        public override void WriteKnownResponseElement(RequestSecurityTokenResponse rstr, XmlWriter writer, WSTrustSerializationContext context)
        {
            if (rstr == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rstr");
            }

            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

            if (context == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
            }

            WSTrustSerializationHelper.WriteKnownResponseElement(rstr, writer, context, this, WSTrustConstantsAdapter.TrustFeb2005);
        }
Example #15
0
        /// <summary>
        /// Override of the base class that Reads a specific child element inside the RSTR.
        /// </summary>
        /// <param name="reader">Reader pointing at an element to read inside the RSTR.</param>
        /// <param name="rstr">The RequestSecurityTokenResponse element that is being populated from the reader.</param>
        /// <param name="context">Current Serialization context.</param>
        /// <exception cref="ArgumentNullException">Either reader or rstr or context parameter is null.</exception>
        /// <exception cref="WSTrustSerializationException">Unable to deserialize the current parameter.</exception>
        public override void ReadXmlElement(XmlReader reader, RequestSecurityTokenResponse rstr, WSTrustSerializationContext context)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            if (rstr == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rstr");
            }

            if (context == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
            }

            WSTrustSerializationHelper.ReadRSTRXml(reader, rstr, context, WSTrustConstantsAdapter.TrustFeb2005);
        }
        /// <summary>
        /// Writes out the supported elements on the response object. 
        /// </summary>
        /// <param name="rstr">The response instance</param>
        /// <param name="writer">The writer to write to</param>
        /// <param name="context">Current Serialization context.</param>
        /// <exception cref="ArgumentNullException">Either rstr or writer or context parameter is null.</exception>
        public override void WriteKnownResponseElement(RequestSecurityTokenResponse rstr, XmlWriter writer, WSTrustSerializationContext context)
        {
            if (rstr == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rstr");
            }

            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

            if (context == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
            }

            WSTrustSerializationHelper.WriteKnownResponseElement(rstr, writer, context, this, WSTrustConstantsAdapter.TrustFeb2005);
        }
        /// <summary>
        /// Override of the base class that Reads a specific child element inside the RSTR.
        /// </summary>
        /// <param name="reader">Reader pointing at an element to read inside the RSTR.</param>
        /// <param name="rstr">The RequestSecurityTokenResponse element that is being populated from the reader.</param>
        /// <param name="context">Current Serialization context.</param>
        /// <exception cref="ArgumentNullException">Either reader or rstr or context parameter is null.</exception>
        /// <exception cref="WSTrustSerializationException">Unable to deserialize the current parameter.</exception>
        public override void ReadXmlElement(XmlReader reader, RequestSecurityTokenResponse rstr, WSTrustSerializationContext context)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            if (rstr == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rstr");
            }

            if (context == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
            }

            WSTrustSerializationHelper.ReadRSTRXml(reader, rstr, context, WSTrustConstantsAdapter.TrustFeb2005);
        }
        public async Task<SignInResponseMessage> GenerateAsync(SignInRequestMessage request, WindowsPrincipal windowsPrincipal)
        {
            Logger.Info("Creating WS-Federation signin response");

            // create subject
            var outgoingSubject = SubjectGenerator.Create(windowsPrincipal, _options);

            // call custom claims tranformation logic
            var context = new CustomClaimsProviderContext
            {
                WindowsPrincipal = windowsPrincipal,
                OutgoingSubject = outgoingSubject
            };
            await _options.CustomClaimsProvider.TransformAsync(context);

            // create token for user
            var token = CreateSecurityToken(context.OutgoingSubject);

            // return response
            var rstr = new RequestSecurityTokenResponse
            {
                AppliesTo = new EndpointReference(_options.IdpRealm),
                Context = request.Context,
                ReplyTo = _options.IdpReplyUrl,
                RequestedSecurityToken = new RequestedSecurityToken(token)
            };

            var serializer = new WSFederationSerializer(
                new WSTrust13RequestSerializer(),
                new WSTrust13ResponseSerializer());

            var mgr = SecurityTokenHandlerCollectionManager.CreateEmptySecurityTokenHandlerCollectionManager();
            mgr[SecurityTokenHandlerCollectionManager.Usage.Default] = CreateSupportedSecurityTokenHandler();

            var responseMessage = new SignInResponseMessage(
                new Uri(_options.IdpReplyUrl),
                rstr,
                serializer,
                new WSTrustSerializationContext(mgr));

            return responseMessage;
        }
        private static SecurityToken IssueLocalSecurityToken(SecurityToken foreignToken, string RP_Endpoint, string appliesTo, out RequestSecurityTokenResponse RSTR, string keyType = KeyTypes.Bearer)
        {
            if (String.IsNullOrWhiteSpace(RP_Endpoint)) throw new ArgumentNullException("RP_Endpoint");

            Binding binding = null;

            // Authenticate with a SAML Bearer token
            var WsHttpBinding = new WS2007FederationHttpBinding(WSFederationHttpSecurityMode.TransportWithMessageCredential);
            WsHttpBinding.Security.Message.EstablishSecurityContext = false;
            WsHttpBinding.Security.Message.NegotiateServiceCredential = false;
            WsHttpBinding.Security.Message.IssuedKeyType = SecurityKeyType.BearerKey;
            binding = WsHttpBinding;

            // Define the STS endpoint
            EndpointAddress endpoint = new EndpointAddress(new Uri(RP_Endpoint));

            var factory = new WSTrustChannelFactory(binding, endpoint) { TrustVersion = TrustVersion.WSTrust13 };
            factory.Credentials.SupportInteractive = false; // avoid that Cardspace dialog

            // Now we define the Request for Security Token (RST)
            RequestSecurityToken RST = new RequestSecurityToken()
            {
                //identifiy which local token we want
                AppliesTo = new EndpointReference(appliesTo),
                //identify what type of request this is (Issue or Validate)
                RequestType = RequestTypes.Issue,
                //set what kind of token we want returned (appliesTo will override this)
                TokenType = tokenType,
                //set the keytype (symmetric, asymmetric (pub key) or bearer - null = Sender Vouches)
                KeyType = null
            };

            //create the channel (using the SAML token received from the WSC)
            IWSTrustChannelContract channel = factory.CreateChannelWithIssuedToken(foreignToken);

            //send the token issuance command
            SecurityToken token = channel.Issue(RST, out RSTR);

            return token;
        }
        /// <summary>
        /// Initializes an instance of <see cref="WSTrustResponseBodyWriter"/>
        /// </summary>
        /// <param name="requestSecurityTokenResponse">The Response object that can write the body contents.</param>
        /// <param name="serializer">Serializer to use for serializing the RSTR.</param>
        /// <param name="context">The <see cref="WSTrustSerializationContext"/> of this request.</param>
        /// <exception cref="ArgumentNullException">serializer parameter is null.</exception>
        public WSTrustResponseBodyWriter(RSTR requestSecurityTokenResponse, WSTrustResponseSerializer serializer, WSTrustSerializationContext context)
            : base( true )
        {
            if ( serializer == null )
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "serializer" );
            }

            if ( requestSecurityTokenResponse == null )
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("requestSecurityTokenResponse");
            }

            if ( context == null )
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "context" );
            }

            _serializer = serializer;
            _rstr = requestSecurityTokenResponse;
            _context = context;
        }
        /// <summary>
        /// Initializes an instance of <see cref="WSTrustResponseBodyWriter"/>
        /// </summary>
        /// <param name="requestSecurityTokenResponse">The Response object that can write the body contents.</param>
        /// <param name="serializer">Serializer to use for serializing the RSTR.</param>
        /// <param name="context">The <see cref="WSTrustSerializationContext"/> of this request.</param>
        /// <exception cref="ArgumentNullException">serializer parameter is null.</exception>
        public WSTrustResponseBodyWriter(RSTR requestSecurityTokenResponse, WSTrustResponseSerializer serializer, WSTrustSerializationContext context)
            : base(true)
        {
            if (serializer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("serializer");
            }

            if (requestSecurityTokenResponse == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("requestSecurityTokenResponse");
            }

            if (context == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
            }

            _serializer = serializer;
            _rstr       = requestSecurityTokenResponse;
            _context    = context;
        }
        /// <summary>
        /// Sets the appropriate things, such as requested security token, inside the RSTR 
        /// based on what is inside this token descriptor instance.  
        /// </summary>
        /// <param name="response">The RSTR object that this security token descriptor needs to modify.</param>
        /// <exception cref="ArgumentNullException">When response is null.</exception>
        public virtual void ApplyTo(RSTR response)
        {
            if (response == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("response");
            }

            if (tokenType != null)
            {
                response.TokenType = tokenType;
            }

            if (token != null)
            {
                response.RequestedSecurityToken = new RequestedSecurityToken(token);
            }

            if (attachedReference != null)
            {
                response.RequestedAttachedReference = attachedReference;
            }

            if (unattachedReference != null)
            {
                response.RequestedUnattachedReference = unattachedReference;
            }

            if (lifetime != null)
            {
                response.Lifetime = lifetime;
            }

            if (proofDescriptor != null)
            {
                proofDescriptor.ApplyTo(response);
            }
        }
        /// <summary>
        /// Sets the appropriate things, such as requested security token, inside the RSTR
        /// based on what is inside this token descriptor instance.
        /// </summary>
        /// <param name="response">The RSTR object that this security token descriptor needs to modify.</param>
        /// <exception cref="ArgumentNullException">When response is null.</exception>
        public virtual void ApplyTo(RSTR response)
        {
            if (response == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("response");
            }

            if (tokenType != null)
            {
                response.TokenType = tokenType;
            }

            if (token != null)
            {
                response.RequestedSecurityToken = new RequestedSecurityToken(token);
            }

            if (attachedReference != null)
            {
                response.RequestedAttachedReference = attachedReference;
            }

            if (unattachedReference != null)
            {
                response.RequestedUnattachedReference = unattachedReference;
            }

            if (lifetime != null)
            {
                response.Lifetime = lifetime;
            }

            if (proofDescriptor != null)
            {
                proofDescriptor.ApplyTo(response);
            }
        }
Example #24
0
        /// <summary>
        /// Creates the RSTR and finally read the information from TokenDescriptor and apply
        /// those to the RSTR.
        /// </summary>
        /// <param name="request">The RST from the request.</param>
        /// <param name="tokenDescriptor">The token descriptor which contains the information for the issued token.</param>
        /// <returns>The RSTR for the response, null if the token descriptor is null.</returns>
        protected virtual RSTR GetResponse(RST request, SecurityTokenDescriptor tokenDescriptor)
        {
            if (tokenDescriptor != null)
            {
                RSTR rstr = new RSTR(request);
                tokenDescriptor.ApplyTo(rstr);

                // Set the replyTo address of the relying party (if any) in the outgoing RSTR from the generated
                // token descriptor (STD)  based on the table below:
                //
                // RST.ReplyTo       STD.ReplyToAddress            RSTR.ReplyTo
                // ===========       ====================          ============
                // Set               Not Set                       Not Set
                // Set               Set                           Set to STD.ReplyToAddress
                // Not Set           Not Set                       Not Set
                // Not Set           Set                           Not Set
                //
                if (request.ReplyTo != null)
                {
                    rstr.ReplyTo = tokenDescriptor.ReplyToAddress;
                }

                //
                // Set the appliesTo address (if any) in the outgoing RSTR from the generated token descriptor.
                //
                if (!string.IsNullOrEmpty(tokenDescriptor.AppliesToAddress))
                {
                    rstr.AppliesTo = new EndpointReference(tokenDescriptor.AppliesToAddress);
                }

                return(rstr);
            }
            else
            {
                return(null);
            }
        }
Example #25
0
		public virtual void ApplyTo (RequestSecurityTokenResponse response) {
			throw new NotImplementedException ();
		}
        /// <summary>
        /// Serializes a RequestSecurityTokenResponse object to the given XmlWriter
        /// stream.
        /// </summary>
        /// <param name="response">RequestSecurityTokenResponse object that needs to be serialized to the writer.</param>
        /// <param name="writer">XmlWriter into which the object will be serialized</param>
        /// <param name="context">Current Serialization context.</param>
        /// <exception cref="ArgumentNullException">The given response or writer or context parameter is null</exception>
        public override void WriteXml(RequestSecurityTokenResponse response, XmlWriter writer, WSTrustSerializationContext context)
        {
            if (response == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("response");
            }

            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

            if (context == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
            }

            if (response.IsFinal)
            {
                writer.WriteStartElement(WSTrust13Constants.Prefix, WSTrust13Constants.ElementNames.RequestSecurityTokenResponseCollection, WSTrust13Constants.NamespaceURI);
            }

            WSTrustSerializationHelper.WriteResponse(response, writer, context, this, WSTrustConstantsAdapter.Trust13);

            if (response.IsFinal)
            {
                writer.WriteEndElement();
            }
        }
        /// <summary>
        /// Override of the Base class method that writes a specific RSTR parameter to the outgoing stream.
        /// </summary>
        /// <param name="writer">Writer to which the RSTR is serialized</param>
        /// <param name="elementName">The Local name of the element to be written.</param>
        /// <param name="elementValue">The value of the element.</param>
        /// <param name="rstr">The entire RSTR object that is being serialized.</param>
        /// <param name="context">Current Serialization context.</param>
        /// <exception cref="ArgumentNullException">Either writer or rstr or context is null.</exception>
        /// <exception cref="ArgumentException">elementName is null or an empty string.</exception>
        public override void WriteXmlElement(XmlWriter writer, string elementName, object elementValue, RequestSecurityTokenResponse rstr, WSTrustSerializationContext context)
        {
            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

            if (string.IsNullOrEmpty(elementName))
            {
                throw DiagnosticUtility.ThrowHelperArgumentNullOrEmptyString("elementName");
            }

            if (rstr == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rstr");
            }

            if (context == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
            }

            WSTrustSerializationHelper.WriteRSTRXml(writer, elementName, elementValue, context, WSTrustConstantsAdapter.TrustFeb2005);
        }
 /// <summary>
 /// When overriden in the derived class serializes the given RequestSecurityTokenResponse into the XmlWriter
 /// </summary>
 /// <param name="response">RequestSecurityTokenRespone object to be serializes</param>
 /// <param name="writer">XML writer to serialize into</param>
 /// <param name="context">Current Serialization context.</param>
 public abstract void WriteXml(RequestSecurityTokenResponse response, XmlWriter writer, WSTrustSerializationContext context);
        /// <summary>
        /// Creates the RSTR and finally read the information from TokenDescriptor and apply 
        /// those to the RSTR.
        /// </summary>
        /// <param name="request">The RST from the request.</param>
        /// <param name="tokenDescriptor">The token descriptor which contains the information for the issued token.</param>
        /// <returns>The RSTR for the response, null if the token descriptor is null.</returns>
        protected virtual RSTR GetResponse(RST request, SecurityTokenDescriptor tokenDescriptor)
        {
            if (tokenDescriptor != null)
            {
                RSTR rstr = new RSTR(request);
                tokenDescriptor.ApplyTo(rstr);

                // Set the replyTo address of the relying party (if any) in the outgoing RSTR from the generated 
                // token descriptor (STD)  based on the table below:
                //
                // RST.ReplyTo       STD.ReplyToAddress            RSTR.ReplyTo
                // ===========       ====================          ============
                // Set               Not Set                       Not Set
                // Set               Set                           Set to STD.ReplyToAddress
                // Not Set           Not Set                       Not Set
                // Not Set           Set                           Not Set
                //
                if (request.ReplyTo != null)
                {
                    rstr.ReplyTo = tokenDescriptor.ReplyToAddress;
                }

                //
                // Set the appliesTo address (if any) in the outgoing RSTR from the generated token descriptor. 
                //
                if (!string.IsNullOrEmpty(tokenDescriptor.AppliesToAddress))
                {
                    rstr.AppliesTo = new EndpointReference(tokenDescriptor.AppliesToAddress);
                }

                return rstr;
            }
            else
            {
                return null;
            }
        }
        public static void ReadRSTRXml(XmlReader reader, RequestSecurityTokenResponse rstr, WSTrustSerializationContext context, WSTrustConstantsAdapter trustConstants)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            if (rstr == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rstr");
            }

            if (context == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
            }

            if (trustConstants == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("trustConstants");
            }

            if (reader.IsStartElement(trustConstants.Elements.Entropy, trustConstants.NamespaceURI))
            {
                if (!reader.IsEmptyElement)
                {
                    reader.ReadStartElement(trustConstants.Elements.Entropy, trustConstants.NamespaceURI);

                    ProtectedKey protectedKey = ReadProtectedKey(reader, context, trustConstants);
                    if (protectedKey == null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3026)));
                    }

                    rstr.Entropy = new Entropy(protectedKey);

                    reader.ReadEndElement();
                }

                if (rstr.Entropy == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3026)));
                }

                return;
            }

            if (reader.IsStartElement(trustConstants.Elements.KeySize, trustConstants.NamespaceURI))
            {
                if (!reader.IsEmptyElement)
                {
                    rstr.KeySizeInBits = Convert.ToInt32(reader.ReadElementContentAsString(), CultureInfo.InvariantCulture);
                }

                if (rstr.KeySizeInBits == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3154)));
                }

                return;
            }

            if (reader.IsStartElement(trustConstants.Elements.RequestType, trustConstants.NamespaceURI))
            {
                rstr.RequestType = WSTrustSerializationHelper.ReadRequestType(reader, trustConstants);
                return;
            }

            if (reader.IsStartElement(trustConstants.Elements.Lifetime, trustConstants.NamespaceURI))
            {
                rstr.Lifetime = WSTrustSerializationHelper.ReadLifetime(reader, trustConstants);
                return;
            }

            if (reader.IsStartElement(trustConstants.Elements.RequestedSecurityToken, trustConstants.NamespaceURI))
            {
                if (!reader.IsEmptyElement)
                {
                    rstr.RequestedSecurityToken = new RequestedSecurityToken(WSTrustSerializationHelper.ReadInnerXml(reader));
                }

                if (rstr.RequestedSecurityToken == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3158)));
                }

                return;
            }

            if (reader.IsStartElement(WSPolicyConstants.ElementNames.AppliesTo, WSPolicyConstants.NamespaceURI))
            {
                rstr.AppliesTo = WSTrustSerializationHelper.ReadAppliesTo(reader, trustConstants);
                return;
            }

            if (reader.IsStartElement(trustConstants.Elements.RequestedProofToken, trustConstants.NamespaceURI))
            {
                if (!reader.IsEmptyElement)
                {
                    reader.ReadStartElement();

                    if ((reader.LocalName == trustConstants.Elements.ComputedKey) && (reader.NamespaceURI == trustConstants.NamespaceURI))
                    {
                        rstr.RequestedProofToken = new RequestedProofToken(ReadComputedKeyAlgorithm(reader, trustConstants));
                    }
                    else
                    {
                        ProtectedKey protectedKey = ReadProtectedKey(reader, context, trustConstants);

                        if (protectedKey == null)
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3025)));
                        }

                        rstr.RequestedProofToken = new RequestedProofToken(protectedKey);
                    }

                    reader.ReadEndElement();
                }

                if (rstr.RequestedProofToken == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3025)));
                }

                return;
            }

            if (reader.IsStartElement(trustConstants.Elements.RequestedAttachedReference, trustConstants.NamespaceURI))
            {
                if (!reader.IsEmptyElement)
                {
                    reader.ReadStartElement();
                    rstr.RequestedAttachedReference = context.SecurityTokenHandlers.ReadKeyIdentifierClause(reader);
                    reader.ReadEndElement();
                }

                if (rstr.RequestedAttachedReference == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3159)));
                }

                return;
            }

            if (reader.IsStartElement(trustConstants.Elements.RequestedUnattachedReference, trustConstants.NamespaceURI))
            {
                if (!reader.IsEmptyElement)
                {
                    reader.ReadStartElement();
                    rstr.RequestedUnattachedReference = context.SecurityTokenHandlers.ReadKeyIdentifierClause(reader);
                    reader.ReadEndElement();
                }

                if (rstr.RequestedUnattachedReference == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3160)));
                }

                return;
            }

            if (reader.IsStartElement(trustConstants.Elements.TokenType, trustConstants.NamespaceURI))
            {
                rstr.TokenType = reader.ReadElementContentAsString();
                if (!UriUtil.CanCreateValidUri(rstr.TokenType, UriKind.Absolute))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3135, trustConstants.Elements.TokenType, trustConstants.NamespaceURI, rstr.TokenType)));
                }

                return;
            }

            if (reader.IsStartElement(trustConstants.Elements.KeyType, trustConstants.NamespaceURI))
            {
                rstr.KeyType = WSTrustSerializationHelper.ReadKeyType(reader, trustConstants);
                return;
            }

            if (reader.IsStartElement(trustConstants.Elements.AuthenticationType, trustConstants.NamespaceURI))
            {
                rstr.AuthenticationType = reader.ReadElementContentAsString(trustConstants.Elements.AuthenticationType, trustConstants.NamespaceURI);
                if (!UriUtil.CanCreateValidUri(rstr.AuthenticationType, UriKind.Absolute))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3135, trustConstants.Elements.AuthenticationType, trustConstants.NamespaceURI, rstr.AuthenticationType)));
                }

                return;
            }

            if (reader.IsStartElement(trustConstants.Elements.EncryptionAlgorithm, trustConstants.NamespaceURI))
            {
                rstr.EncryptionAlgorithm = reader.ReadElementContentAsString(trustConstants.Elements.EncryptionAlgorithm, trustConstants.NamespaceURI);
                if (!UriUtil.CanCreateValidUri(rstr.EncryptionAlgorithm, UriKind.Absolute))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3135, trustConstants.Elements.EncryptionAlgorithm, trustConstants.NamespaceURI, rstr.EncryptionAlgorithm)));
                }

                return;
            }

            if (reader.IsStartElement(trustConstants.Elements.CanonicalizationAlgorithm, trustConstants.NamespaceURI))
            {
                rstr.CanonicalizationAlgorithm = reader.ReadElementContentAsString(trustConstants.Elements.CanonicalizationAlgorithm, trustConstants.NamespaceURI);
                if (!UriUtil.CanCreateValidUri(rstr.CanonicalizationAlgorithm, UriKind.Absolute))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3135, trustConstants.Elements.CanonicalizationAlgorithm, trustConstants.NamespaceURI, rstr.CanonicalizationAlgorithm)));
                }

                return;
            }

            if (reader.IsStartElement(trustConstants.Elements.SignatureAlgorithm, trustConstants.NamespaceURI))
            {
                rstr.SignatureAlgorithm = reader.ReadElementContentAsString(trustConstants.Elements.SignatureAlgorithm, trustConstants.NamespaceURI);
                if (!UriUtil.CanCreateValidUri(rstr.SignatureAlgorithm, UriKind.Absolute))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3135, trustConstants.Elements.SignatureAlgorithm, trustConstants.NamespaceURI, rstr.SignatureAlgorithm)));
                }

                return;
            }

            if (reader.IsStartElement(trustConstants.Elements.SignWith, trustConstants.NamespaceURI))
            {
                rstr.SignWith = reader.ReadElementContentAsString();
                if (!UriUtil.CanCreateValidUri(rstr.SignWith, UriKind.Absolute))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3135, trustConstants.Elements.SignWith, trustConstants.NamespaceURI, rstr.SignWith)));
                }

                return;
            }

            if (reader.IsStartElement(trustConstants.Elements.EncryptWith, trustConstants.NamespaceURI))
            {
                rstr.EncryptWith = reader.ReadElementContentAsString();
                if (!UriUtil.CanCreateValidUri(rstr.EncryptWith, UriKind.Absolute))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3135, trustConstants.Elements.EncryptWith, trustConstants.NamespaceURI, rstr.EncryptWith)));
                }

                return;
            }

            if (reader.IsStartElement(trustConstants.Elements.BinaryExchange, trustConstants.NamespaceURI))
            {
                rstr.BinaryExchange = WSTrustSerializationHelper.ReadBinaryExchange(reader, trustConstants);
                return;
            }

            if (reader.IsStartElement(trustConstants.Elements.Status, trustConstants.NamespaceURI))
            {
                rstr.Status = WSTrustSerializationHelper.ReadStatus(reader, trustConstants);
                return;
            }

            if (reader.IsStartElement(trustConstants.Elements.RequestedTokenCancelled, trustConstants.NamespaceURI))
            {
                rstr.RequestedTokenCancelled = true;
                reader.ReadStartElement();
                return;
            }

            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3007, reader.LocalName, reader.NamespaceURI)));
        }
Example #31
0
        private string SerializeResponse(RequestSecurityTokenResponse response)
        {
            var serializer = new WSTrust13ResponseSerializer();
            var context =
                new WSTrustSerializationContext(
                    FederatedAuthentication.FederationConfiguration.IdentityConfiguration
                        .SecurityTokenHandlerCollectionManager);
            var sb = new StringBuilder(128);

            using (var writer = XmlWriter.Create(new StringWriter(sb)))
            {
                serializer.WriteXml(response, writer, context);
                return sb.ToString();
            }
        }
Example #32
0
        /// <summary>
        /// The callback that is invoked on the completion of the BeginGetOutputSubjects call.
        /// </summary>
        /// <param name="result">The async result.</param>
        /// <exception cref="ArgumentNullException">When the given async result is null.</exception>
        void OnGetOutputClaimsIdentityComplete(IAsyncResult result)
        {
            if (null == result)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("result");
            }

            FederatedAsyncState state = result.AsyncState as FederatedAsyncState;

            if (state == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID2001)));
            }

            SecurityTokenHandler securityTokenHandler = state.SecurityTokenHandler;

            if (securityTokenHandler == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID2016)));
            }

            Exception unhandledException = null;
            RST       request            = state.Request;
            RSTR      response           = null;

            TypedAsyncResult <RSTR> typedResult = state.Result as TypedAsyncResult <RSTR>;

            if (typedResult == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID2004, typeof(TypedAsyncResult <RSTR>), state.Result.GetType())));
            }

            try
            {
                //
                // get token descriptor
                //
                if (_tokenDescriptor == null)
                {
                    throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID2003));
                }
                // Step 7: Retrieve the output claims to be included in the issued-token
                _tokenDescriptor.Subject = EndGetOutputClaimsIdentity(result);

                //
                // Use the retrieved securityTokenHandler to create and setup the issued token information on the tokenDescriptor
                // (actual issued token, AttachedReference and UnattachedReference)
                // TokenType is preserved from the request if possible
                if (!string.IsNullOrEmpty(request.TokenType))
                {
                    _tokenDescriptor.TokenType = request.TokenType;
                }
                else
                {
                    string[] identifiers = securityTokenHandler.GetTokenTypeIdentifiers();
                    if (identifiers == null || identifiers.Length == 0)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID4264, request.TokenType)));
                    }
                    _tokenDescriptor.TokenType = identifiers[0];
                }
                _tokenDescriptor.Token               = securityTokenHandler.CreateToken(_tokenDescriptor);
                _tokenDescriptor.AttachedReference   = securityTokenHandler.CreateSecurityTokenReference(_tokenDescriptor.Token, true);
                _tokenDescriptor.UnattachedReference = securityTokenHandler.CreateSecurityTokenReference(_tokenDescriptor.Token, false);

                // 9. Create the RSTR
                response = GetResponse(request, _tokenDescriptor);
            }
#pragma warning suppress 56500
            catch (Exception e)
            {
                if (System.Runtime.Fx.IsFatal(e))
                {
                    throw;
                }

                unhandledException = e;
            }

            typedResult.Complete(response, typedResult.CompletedSynchronously, unhandledException);
        }
Example #33
0
        /// <summary>
        /// Issues a Security Token.
        /// </summary>
        /// <param name="principal">The identity of the token requestor.</param>
        /// <param name="request">The request.</param>
        /// <returns>The response.</returns>
        public virtual RSTR Issue(ClaimsPrincipal principal, RST request)
        {
            if (request == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("request");
            }

            _principal = principal;
            _request   = request;

            // 1. Do request validation
            ValidateRequest(request);

            // 2. Get the scope and populate into tokenDescriptor
            Scope scope = GetScope(principal, request);

            if (scope == null)
            {
                throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID2013));
            }
            this.Scope = scope;


            // Create the security token descriptor now that we have a scope.
            this.SecurityTokenDescriptor = CreateSecurityTokenDescriptor(request, scope);
            if (this.SecurityTokenDescriptor == null)
            {
                throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID2003));
            }

            if (this.SecurityTokenDescriptor.SigningCredentials == null)
            {
                throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID2079));
            }

            //
            // If TokenEncryptionRequired is set to true, then we must encrypt the token.
            //
            if (this.Scope.TokenEncryptionRequired && this.SecurityTokenDescriptor.EncryptingCredentials == null)
            {
                throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4184));
            }

            // 3. Get the token-handler
            SecurityTokenHandler securityTokenHandler = GetSecurityTokenHandler(request.TokenType);

            if (securityTokenHandler == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.ID4010, request.TokenType)));
            }


            // 4. Get the issuer name and populate into tokenDescriptor
            _tokenDescriptor.TokenIssuerName = GetValidIssuerName();

            // 5. Get the token lifetime and populate into tokenDescriptor
            _tokenDescriptor.Lifetime = GetTokenLifetime(request.Lifetime);

            // 6. Get the proof token and populate into tokenDescriptor
            _tokenDescriptor.Proof = GetProofToken(request, scope);

            // 7. Get the subjects and populate into tokenDescriptor
            _tokenDescriptor.Subject = GetOutputClaimsIdentity(principal, request, scope);

            // use the securityTokenHandler from Step 3 to create and setup the issued token information on the tokenDescriptor
            // (actual issued token, AttachedReference and UnattachedReference)
            // TokenType is preserved from the request if possible
            if (!string.IsNullOrEmpty(request.TokenType))
            {
                _tokenDescriptor.TokenType = request.TokenType;
            }
            else
            {
                string[] identifiers = securityTokenHandler.GetTokenTypeIdentifiers();
                if (identifiers == null || identifiers.Length == 0)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID4264, request.TokenType)));
                }
                _tokenDescriptor.TokenType = identifiers[0];
            }
            _tokenDescriptor.Token               = securityTokenHandler.CreateToken(_tokenDescriptor);
            _tokenDescriptor.AttachedReference   = securityTokenHandler.CreateSecurityTokenReference(_tokenDescriptor.Token, true);
            _tokenDescriptor.UnattachedReference = securityTokenHandler.CreateSecurityTokenReference(_tokenDescriptor.Token, false);

            // 9. Create the RSTR
            RSTR rstr = GetResponse(request, _tokenDescriptor);

            return(rstr);
        }
        /// <summary>
        /// Sets the appropriate things, such as requested proof token, inside the RSTR 
        /// based on what is inside the proof descriptor instance.  
        /// </summary>
        /// <param name="response">The RSTR object that this proof descriptor needs to modify.</param>
        /// <exception cref="ArgumentNullException">When the response is null.</exception>
        public override void ApplyTo(RSTR response)
        {
            if (response == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("response");
            }

            if (_targetEntropy != null)
            {
                //
                // When there is target entropy, then we will send back a computedKeyalgorithm
                // in the proof token case and send the entropy as response.Entropy. By default, this
                // class is doing Psha1.
                //
                response.RequestedProofToken = new RequestedProofToken(ComputedKeyAlgorithms.Psha1);
                response.KeySizeInBits = _keySizeInBits;
                response.Entropy = new Entropy(_targetEntropy, _requestorWrappingCredentials);
            }
            else
            {
                //
                // When there is no target entroypy, then we will send back the key either in
                // binary secret format or in the encrypted key format
                //
                response.RequestedProofToken = new RequestedProofToken(_key, _requestorWrappingCredentials);
            }
        }
 /// <summary>
 /// When overridden in the derived class reads a child element inside RSTR.
 /// </summary>
 /// <param name="reader">Reader pointing at an element to read inside the RSTR.</param>
 /// <param name="requestSecurityTokenResponse">The RequestSecurityTokenResponse element that is being populated from the reader.</param>
 /// <param name="context">Current Serialization context.</param>
 public abstract void ReadXmlElement(XmlReader reader, RequestSecurityTokenResponse requestSecurityTokenResponse, WSTrustSerializationContext context);
        public static void WriteResponse(RequestSecurityTokenResponse response, XmlWriter writer, WSTrustSerializationContext context, WSTrustResponseSerializer responseSerializer, WSTrustConstantsAdapter trustConstants)
        {
            if (response == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("response");
            }

            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

            if (context == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
            }

            if (responseSerializer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("responseSerializer");
            }

            if (trustConstants == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("trustConstants");
            }

            responseSerializer.Validate(response);

            // Step 1: Write RSTR start element
            writer.WriteStartElement(trustConstants.Prefix, trustConstants.Elements.RequestSecurityTokenResponse, trustConstants.NamespaceURI);

            // Step 2: Write known RSTR attributes, i.e. Context
            if (!string.IsNullOrEmpty(response.Context))
            {
                writer.WriteAttributeString(trustConstants.Attributes.Context, response.Context);
            }

            // Step 3: Write known RSTR elements
            responseSerializer.WriteKnownResponseElement(response, writer, context);

            // Step 4: Write custom RSTR elements
            foreach (KeyValuePair<string, object> messageParam in response.Properties)
            {
                responseSerializer.WriteXmlElement(writer, messageParam.Key, messageParam.Value, response, context);
            }

            // Step 5: Write RSTR end element to close it
            writer.WriteEndElement();
        }
Example #37
0
        /// <summary>
        /// Override of the Base class method that writes a specific RSTR parameter to the outgoing stream.
        /// </summary>
        /// <param name="writer">Writer to which the RSTR is serialized</param>
        /// <param name="elementName">The Local name of the element to be written.</param>
        /// <param name="elementValue">The value of the element.</param>
        /// <param name="rstr">The entire RSTR object that is being serialized.</param>
        /// <param name="context">Current Serialization context.</param>
        /// <exception cref="ArgumentNullException">Either writer or rstr or context is null.</exception>
        /// <exception cref="ArgumentException">elementName is null or an empty string.</exception>
        public override void WriteXmlElement(XmlWriter writer, string elementName, object elementValue, RequestSecurityTokenResponse rstr, WSTrustSerializationContext context)
        {
            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

            if (string.IsNullOrEmpty(elementName))
            {
                throw DiagnosticUtility.ThrowHelperArgumentNullOrEmptyString("elementName");
            }

            if (rstr == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rstr");
            }

            if (context == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
            }

            WSTrustSerializationHelper.WriteRSTRXml(writer, elementName, elementValue, context, WSTrustConstantsAdapter.TrustFeb2005);
        }
        private static XmlElement ExtractTokenXml(RequestSecurityTokenResponse rstr)
        {
            if (rstr.RequestedSecurityToken.SecurityToken != null)
            {
                var xmlString = rstr.RequestedSecurityToken.SecurityToken.ToTokenXmlString();
                return XElement.Parse(xmlString).ToXmlElement();
            }
            if (rstr.RequestedSecurityToken.SecurityTokenXml != null)
            {
                return rstr.RequestedSecurityToken.SecurityTokenXml;
            }

            return null;
        }
Example #39
0
		public abstract void ApplyTo (RequestSecurityTokenResponse response);
 /// <summary>
 /// When overriden in the derived class serializes the given RequestSecurityTokenResponse into the XmlWriter
 /// </summary>
 /// <param name="response">RequestSecurityTokenRespone object to be serializes</param>
 /// <param name="writer">XML writer to serialize into</param>
 /// <param name="context">Current Serialization context.</param>
 public abstract void WriteXml(RequestSecurityTokenResponse response, XmlWriter writer, WSTrustSerializationContext context);
        internal static SecurityToken ComputeProofKey(RequestSecurityToken rst, RequestSecurityTokenResponse rstr)
        {
            if (rstr.Entropy == null)
            {
                throw new NotSupportedException("RSTR entropy is null");
            }
            if (rst.Entropy == null)
            {
                throw new NotSupportedException("RST entropy is null");
            }

            int? keySizeInBits = rst.KeySizeInBits;
            int num = keySizeInBits.HasValue ? keySizeInBits.GetValueOrDefault() : 0x400;
            if (rstr.KeySizeInBits.HasValue)
            {
                num = rstr.KeySizeInBits.Value;
            }

            return new BinarySecretSecurityToken(
                KeyGenerator.ComputeCombinedKey(
                    rst.Entropy.GetKeyBytes(),
                    rstr.Entropy.GetKeyBytes(),
                    num));
        }
        /// <summary>
        /// Override of the Base class method that writes a specific RSTR parameter to the outgoing stream.
        /// </summary>
        /// <param name="writer">Writer to which the RSTR is serialized</param>
        /// <param name="elementName">The Local name of the element to be written.</param>
        /// <param name="elementValue">The value of the element.</param>
        /// <param name="rstr">The entire RSTR object that is being serialized.</param>
        /// <param name="context">Current Serialization context.</param>
        /// <exception cref="ArgumentNullException">Either writer or rstr or context is null.</exception>
        /// <exception cref="ArgumentException">elementName is null or an empty string.</exception>
        public override void WriteXmlElement(XmlWriter writer, string elementName, object elementValue, RequestSecurityTokenResponse rstr, WSTrustSerializationContext context)
        {
            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

            if (string.IsNullOrEmpty(elementName))
            {
                throw DiagnosticUtility.ThrowHelperArgumentNullOrEmptyString("elementName");
            }

            if (rstr == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rstr");
            }

            if (context == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
            }

            if (StringComparer.Ordinal.Equals(elementName, WSTrust13Constants.ElementNames.KeyWrapAlgorithm))
            {
                writer.WriteElementString(WSTrust13Constants.Prefix, WSTrust13Constants.ElementNames.KeyWrapAlgorithm, WSTrust13Constants.NamespaceURI, (string)elementValue);
                return;
            }

            WSTrustSerializationHelper.WriteRSTRXml(writer, elementName, elementValue, context, WSTrustConstantsAdapter.Trust13);
        }
 /// <summary>
 /// When overridden in the derived class reads a child element inside RSTR.
 /// </summary>
 /// <param name="reader">Reader pointing at an element to read inside the RSTR.</param>
 /// <param name="requestSecurityTokenResponse">The RequestSecurityTokenResponse element that is being populated from the reader.</param>
 /// <param name="context">Current Serialization context.</param>
 public abstract void ReadXmlElement(XmlReader reader, RequestSecurityTokenResponse requestSecurityTokenResponse, WSTrustSerializationContext context);
        /// <summary>
        /// Override of the Base class method that writes a specific RSTR parameter to the outgoing stream.
        /// </summary>
        /// <param name="writer">Writer to which the RSTR is serialized</param>
        /// <param name="elementName">The Local name of the element to be written.</param>
        /// <param name="elementValue">The value of the element.</param>
        /// <param name="rstr">The entire RSTR object that is being serialized.</param>
        /// <param name="context">Current Serialization context.</param>
        /// <exception cref="ArgumentNullException">Either writer or rstr or context is null.</exception>
        /// <exception cref="ArgumentException">elementName is null or an empty string.</exception>
        public override void WriteXmlElement(XmlWriter writer, string elementName, object elementValue, RequestSecurityTokenResponse rstr, WSTrustSerializationContext context)
        {
            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

            if (string.IsNullOrEmpty(elementName))
            {
                throw DiagnosticUtility.ThrowHelperArgumentNullOrEmptyString("elementName");
            }

            if (rstr == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rstr");
            }

            if (context == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
            }

            if (StringComparer.Ordinal.Equals(elementName, WSTrust13Constants.ElementNames.KeyWrapAlgorithm))
            {
                writer.WriteElementString(WSTrust13Constants.Prefix, WSTrust13Constants.ElementNames.KeyWrapAlgorithm, WSTrust13Constants.NamespaceURI, (string)elementValue);
                return;
            }

            WSTrustSerializationHelper.WriteRSTRXml(writer, elementName, elementValue, context, WSTrustConstantsAdapter.Trust13);
        }
 /// <summary>
 /// When overridden in the derived class writes a specific RSTR parameter to the outgoing stream.
 /// </summary>
 /// <param name="writer">Writer to which the RSTR is serialized</param>
 /// <param name="elementName">The Local name of the element to be written.</param>
 /// <param name="elementValue">The value of the element.</param>
 /// <param name="requestSecurityTokenResponse">The entire RSTR object that is being serialized.</param>
 /// <param name="context">Current Serialization context.</param>
 public abstract void WriteXmlElement(XmlWriter writer, string elementName, object elementValue, RequestSecurityTokenResponse requestSecurityTokenResponse, WSTrustSerializationContext context);
        public static void WriteKnownResponseElement(RequestSecurityTokenResponse rstr, XmlWriter writer, WSTrustSerializationContext context, WSTrustResponseSerializer responseSerializer, WSTrustConstantsAdapter trustConstants)
        {
            if (rstr == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rstr");
            }

            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

            if (context == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
            }

            if (responseSerializer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("responseSerializer");
            }

            if (trustConstants == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("trustConstants");
            }

            if (rstr.Entropy != null)
            {
                responseSerializer.WriteXmlElement(writer, trustConstants.Elements.Entropy, rstr.Entropy, rstr, context);
            }

            if (rstr.KeySizeInBits.HasValue)
            {
                responseSerializer.WriteXmlElement(writer, trustConstants.Elements.KeySize, rstr.KeySizeInBits, rstr, context);
            }

            if (rstr.Lifetime != null)
            {
                responseSerializer.WriteXmlElement(writer, trustConstants.Elements.Lifetime, rstr.Lifetime, rstr, context);
            }

            if (rstr.AppliesTo != null)
            {
                responseSerializer.WriteXmlElement(writer, WSPolicyConstants.ElementNames.AppliesTo, rstr.AppliesTo, rstr, context);
            }

            if (rstr.RequestedSecurityToken != null)
            {
                responseSerializer.WriteXmlElement(writer, trustConstants.Elements.RequestedSecurityToken, rstr.RequestedSecurityToken, rstr, context);
            }

            if (rstr.RequestedProofToken != null)
            {
                responseSerializer.WriteXmlElement(writer, trustConstants.Elements.RequestedProofToken, rstr.RequestedProofToken, rstr, context);
            }

            if (rstr.RequestedAttachedReference != null)
            {
                responseSerializer.WriteXmlElement(writer, trustConstants.Elements.RequestedAttachedReference, rstr.RequestedAttachedReference, rstr, context);
            }

            if (rstr.RequestedUnattachedReference != null)
            {
                responseSerializer.WriteXmlElement(writer, trustConstants.Elements.RequestedUnattachedReference, rstr.RequestedUnattachedReference, rstr, context);
            }

            if (!string.IsNullOrEmpty(rstr.SignWith))
            {
                responseSerializer.WriteXmlElement(writer, trustConstants.Elements.SignWith, rstr.SignWith, rstr, context);
            }

            if (!string.IsNullOrEmpty(rstr.EncryptWith))
            {
                responseSerializer.WriteXmlElement(writer, trustConstants.Elements.EncryptWith, rstr.EncryptWith, rstr, context);
            }

            if (!string.IsNullOrEmpty(rstr.TokenType))
            {
                responseSerializer.WriteXmlElement(writer, trustConstants.Elements.TokenType, rstr.TokenType, rstr, context);
            }

            if (!string.IsNullOrEmpty(rstr.RequestType))
            {
                responseSerializer.WriteXmlElement(writer, trustConstants.Elements.RequestType, rstr.RequestType, rstr, context);
            }

            if (!string.IsNullOrEmpty(rstr.KeyType))
            {
                responseSerializer.WriteXmlElement(writer, trustConstants.Elements.KeyType, rstr.KeyType, rstr, context);
            }

            if (!string.IsNullOrEmpty(rstr.AuthenticationType))
            {
                responseSerializer.WriteXmlElement(writer, trustConstants.Elements.AuthenticationType, rstr.AuthenticationType, rstr, context);
            }

            if (!string.IsNullOrEmpty(rstr.EncryptionAlgorithm))
            {
                responseSerializer.WriteXmlElement(writer, trustConstants.Elements.EncryptionAlgorithm, rstr.EncryptionAlgorithm, rstr, context);
            }

            if (!string.IsNullOrEmpty(rstr.CanonicalizationAlgorithm))
            {
                responseSerializer.WriteXmlElement(writer, trustConstants.Elements.CanonicalizationAlgorithm, rstr.CanonicalizationAlgorithm, rstr, context);
            }

            if (!string.IsNullOrEmpty(rstr.SignatureAlgorithm))
            {
                responseSerializer.WriteXmlElement(writer, trustConstants.Elements.SignatureAlgorithm, rstr.SignatureAlgorithm, rstr, context);
            }

            if (rstr.BinaryExchange != null)
            {
                responseSerializer.WriteXmlElement(writer, trustConstants.Elements.BinaryExchange, rstr.BinaryExchange, rstr, context);
            }

            if (rstr.Status != null)
            {
                responseSerializer.WriteXmlElement(writer, trustConstants.Elements.Status, rstr.Status, rstr, context);
            }

            if (rstr.RequestedTokenCancelled)
            {
                responseSerializer.WriteXmlElement(writer, trustConstants.Elements.RequestedTokenCancelled, rstr.RequestedTokenCancelled, rstr, context);
            }
        }
        /// <summary>
        /// Writes out the supported elements on the response object. 
        /// </summary>
        /// <param name="rstr">The response instance</param>
        /// <param name="writer">The writer to write to</param>
        /// <param name="context">Current Serialization context.</param>
        /// <exception cref="ArgumentNullException">Either rstr or writer or context parameter is null.</exception>
        public override void WriteKnownResponseElement(RequestSecurityTokenResponse rstr, XmlWriter writer, WSTrustSerializationContext context)
        {
            if (rstr == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rstr");
            }

            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

            if (context == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
            }

            // Write out the exisiting ones
            WSTrustSerializationHelper.WriteKnownResponseElement(rstr, writer, context, this, WSTrustConstantsAdapter.Trust13);

            // Specific to WS-Trust 13
            if (!string.IsNullOrEmpty(rstr.KeyWrapAlgorithm))
            {
                this.WriteXmlElement(writer, WSTrust13Constants.ElementNames.KeyWrapAlgorithm, rstr.KeyWrapAlgorithm, rstr, context);
            }
        }
 /// <summary>
 /// When overridden in the derived class writes a specific RSTR parameter to the outgoing stream.
 /// </summary>
 /// <param name="writer">Writer to which the RSTR is serialized</param>
 /// <param name="elementName">The Local name of the element to be written.</param>
 /// <param name="elementValue">The value of the element.</param>
 /// <param name="requestSecurityTokenResponse">The entire RSTR object that is being serialized.</param>
 /// <param name="context">Current Serialization context.</param>
 public abstract void WriteXmlElement(XmlWriter writer, string elementName, object elementValue, RequestSecurityTokenResponse requestSecurityTokenResponse, WSTrustSerializationContext context);