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;
        }
        /// <summary>
        /// This method is currently called when serializing ActAs and OBO elements.  Factored shared code.
        /// </summary>
        /// <param name="tokenElement">The <see cref="SecurityTokenElement"/> to write.</param>
        /// <param name="usage">A string defining the SecurityTokenCollection to use.</param>
        /// <param name="context">The <see cref="WSTrustSerializationContext"/> of the request.</param>
        /// <param name="writer">The <see cref="XmlWriter"/> to use.</param>
        private static void WriteTokenElement(SecurityTokenElement tokenElement, string usage, WSTrustSerializationContext context, XmlWriter writer)
        {
            if (tokenElement.SecurityTokenXml != null)
            {
                tokenElement.SecurityTokenXml.WriteTo(writer);
            }
            else
            {
                SecurityTokenHandlerCollection tokenHandlerCollection = null;
                if (context.SecurityTokenHandlerCollectionManager.ContainsKey(usage))
                {
                    tokenHandlerCollection = context.SecurityTokenHandlerCollectionManager[usage];
                }
                else
                {
                    // by default this is the default handler collection, review the WSTrustSerializationContext
                    tokenHandlerCollection = context.SecurityTokenHandlers;
                }

                SecurityToken token = tokenElement.GetSecurityToken();
                bool tokenWritten = false;

                if (tokenHandlerCollection != null && tokenHandlerCollection.CanWriteToken(token))
                {
                    tokenHandlerCollection.WriteToken(writer, token);
                    tokenWritten = true;
                }

                if (!tokenWritten)
                {
                    // by default this is the default handler collection, review the WSTrustSerializationContext
                    context.SecurityTokenHandlers.WriteToken(writer, token);
                }
            }
        }