private static GenericXmlSecurityToken GetSecurityToken(Uri spSiteUrl, string username, string password)
        {
            var binding = new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential)
            {
                TrustVersion = TrustVersion.WSTrustFeb2005
            };
            var address = new EndpointAddress(_stsUrl);

            using (var factory = new Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannelFactory(binding, address))
            {
                factory.Credentials.UserName.UserName = username;
                factory.Credentials.UserName.Password = password;

                var channel = factory.CreateChannel();

                var rst = new RequestSecurityToken
                {
                    RequestType = WSTrustFeb2005Constants.RequestTypes.Issue,
                    KeyType     = WSTrustFeb2005Constants.KeyTypes.Bearer,
                    TokenType   = Microsoft.IdentityModel.Tokens.SecurityTokenTypes.Saml11TokenProfile11,
                    AppliesTo   = new EndpointAddress(spSiteUrl),
                };

                var genericToken = channel.Issue(rst) as GenericXmlSecurityToken;

                return(genericToken);
            }
        }
         public static SecurityToken GetToken(string username, string password, string tokenIssuer, string appliesTo, out RequestSecurityTokenResponse rsts)
 
         {
             WS2007HttpBinding binding = new WS2007HttpBinding();
             binding.Security.Message.EstablishSecurityContext = false;
             binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
             binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
             binding.Security.Mode = SecurityMode.TransportWithMessageCredential;
 
 
             var tokenIssuerUrlFormat = "https://{0}/adfs/services/trust/13/usernamemixed";
             var tokenIssuerUrl = string.Format(tokenIssuerUrlFormat, tokenIssuer);
 
 
             WSTrustChannelFactory trustChannelFactory =
                 new WSTrustChannelFactory(binding, new EndpointAddress(tokenIssuerUrl));
 
             trustChannelFactory.TrustVersion = TrustVersion.WSTrust13;
             trustChannelFactory.Credentials.UserName.UserName = username;
             trustChannelFactory.Credentials.UserName.Password = password;
 
             trustChannelFactory.ConfigureChannelFactory();
 
 
 
             // Create issuance issuance and get security token 
             RequestSecurityToken requestToken = new RequestSecurityToken(WSTrust13Constants.RequestTypes.Issue);
             requestToken.AppliesTo = new EndpointAddress(appliesTo);
 
             WSTrustChannel tokenClient = (WSTrustChannel) trustChannelFactory.CreateChannel();
             SecurityToken token = tokenClient.Issue(requestToken, out rsts);
             return token;
 
         }
        public virtual string AuthenticateUser(string username, string password, string stsEndpoint, string relyingPartyAddress)
        {
            if (string.IsNullOrEmpty(stsEndpoint) || string.IsNullOrEmpty(relyingPartyAddress) ||
                string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                throw new NullReferenceException(
                          "AuthenticationTokenFactory received a null/empty argument for: username || password || stsEndpoint || relyingPartyAddress ");
            }

            var binding = new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential)
            {
                ClientCredentialType = HttpClientCredentialType.None
            };

            var trustChannelFactory = new WSTrustChannelFactory(binding, new EndpointAddress(stsEndpoint))
            {
                TrustVersion = TrustVersion.WSTrust13
            };

            var channelCredentials = trustChannelFactory.Credentials;

            channelCredentials.UserName.UserName  = username;
            channelCredentials.UserName.Password  = password;
            channelCredentials.SupportInteractive = false;

            var tokenClient = (WSTrustChannel)trustChannelFactory.CreateChannel();

            var rst = new RequestSecurityToken(WSTrust13Constants.RequestTypes.Issue, WSTrust13Constants.KeyTypes.Bearer)
            {
                AppliesTo = new System.ServiceModel.EndpointAddress(relyingPartyAddress),
                ReplyTo   = relyingPartyAddress,
                TokenType = "urn:ietf:params:oauth:token-type:jwt"
            };

            var token = tokenClient.Issue(rst);

            var innerXml = ((GenericXmlSecurityToken)token).TokenXml.InnerXml;

            byte[] data = Convert.FromBase64String(innerXml);

            string decodedString = Encoding.UTF8.GetString(data);

            return(decodedString);
        }
        static string _signingCertificateCommonName = "ADFS Signing - adfs.example.local"; // Put the common name of the ADFS Token Signing Certificate here.

        static void Main(string[] args)
        {
            Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannelFactory factory = null;
            try
            {
                _relyingPartyIdentifier = _relyingPartyIdentifier.EndsWith("/") ? _relyingPartyIdentifier : _relyingPartyIdentifier + "/";
                _adfsServerAddress      = _adfsServerAddress.EndsWith("/") ? _adfsServerAddress : _adfsServerAddress + "/";
                factory = new Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannelFactory(new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential), new EndpointAddress(_adfsServerAddress + "adfs/services/trust/13/usernamemixed"));
                factory.TrustVersion = TrustVersion.WSTrust13;
                factory.Credentials.UserName.UserName = _username;
                factory.Credentials.UserName.Password = _password;
                var rst = new Microsoft.IdentityModel.Protocols.WSTrust.RequestSecurityToken
                {
                    RequestType = WSTrust13Constants.RequestTypes.Issue,
                    AppliesTo   = new EndpointAddress(_relyingPartyIdentifier),
                    KeyType     = WSTrust13Constants.KeyTypes.Bearer
                };
                var channel      = factory.CreateChannel();
                var genericToken = channel.Issue(rst) as GenericXmlSecurityToken;
                var handler      = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection();
                var tokenString  = genericToken.TokenXml.OuterXml;
                var samlToken    = handler.ReadToken(new XmlTextReader(new StringReader(tokenString)));
                ValidateSamlToken(samlToken);
            }
            finally
            {
                if (factory != null)
                {
                    try
                    {
                        factory.Close();
                    }
                    catch (CommunicationObjectFaultedException)
                    {
                        factory.Abort();
                    }
                }
            }
        }
Beispiel #5
0
        private static SecurityToken ConvertToToken(string xml)
        {
            WS2007FederationHttpBinding binding = new WS2007FederationHttpBinding(WSFederationHttpSecurityMode.TransportWithMessageCredential,
                false);
            Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannelFactory factory = new Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannelFactory(binding, new EndpointAddress("https://null-EndPoint"));
            factory.TrustVersion = TrustVersion.WSTrustFeb2005;

            Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannel trustChannel = (Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannel)factory.CreateChannel();

            RequestSecurityTokenResponse response = trustChannel.WSTrustResponseSerializer.CreateInstance();
            response.RequestedSecurityToken = new RequestedSecurityToken(LoadXml(xml).DocumentElement);
            response.IsFinal = true;

            RequestSecurityToken requestToken = new RequestSecurityToken(WSTrustFeb2005Constants.RequestTypes.Issue);
            requestToken.KeyType = WSTrustFeb2005Constants.KeyTypes.Symmetric;

            return trustChannel.GetTokenFromResponse(requestToken, response);
        }
        public static string GetAuthenticationCookie(string IdProviderUrl, string RP_Uri, string RP_Realm, string UserName, string Password, string Domain)
        {
            //-----------------------------------------------------------------------------
            // Pass the Windows auth credential to the endpoint of the Identity Provider (ADFS)
            //-----------------------------------------------------------------------------
            var binding = new WS2007HttpBinding(SecurityMode.TransportWithMessageCredential);

            binding.Security.Message.EstablishSecurityContext = false;
            var endpoint = new EndpointAddress(IdProviderUrl + "/adfs/services/trust/13/windowsmixed");
            RequestSecurityTokenResponse rstr;

            using (var factory = new Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannelFactory(binding, endpoint))
            {
                factory.Credentials.Windows.ClientCredential =
                    new NetworkCredential(UserName, Password, Domain);
                factory.TrustVersion = System.ServiceModel.Security.TrustVersion.WSTrust13;

                var rst = new RequestSecurityToken();

                rst.AppliesTo   = new EndpointAddress(RP_Realm);
                rst.KeyType     = WSTrust13Constants.KeyTypes.Bearer;
                rst.RequestType = WSTrust13Constants.RequestTypes.Issue;

                var channel = (Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannel)factory.CreateChannel();
                channel.Issue(rst, out rstr);
            }

            //-----------------------------------------------------------------------------
            // Send the security token acquired from the Identity Provider (ADFS)
            //  to Replying Party (SharePoint)
            // And acquire authorization cookie from SharePoint Server.
            //-----------------------------------------------------------------------------
            using (var output = new StringWriterUtf8(new StringBuilder()))
            {
                using (var xmlwr = XmlWriter.Create(output))
                {
                    WSTrust13ResponseSerializer rs = new WSTrust13ResponseSerializer();
                    rs.WriteXml(rstr, xmlwr, new WSTrustSerializationContext());
                }
                var str = string.Format("wa=wsignin1.0&wctx={0}&wresult={1}",
                                        HttpUtility.UrlEncode(RP_Uri + "/_layouts/15/Authenticate.aspx?Source=%2F"),
                                        HttpUtility.UrlEncode(output.ToString()));

                var req = (HttpWebRequest)HttpWebRequest.Create(RP_Uri + "/_trust/");

                req.Method            = "POST";
                req.ContentType       = "application/x-www-form-urlencoded";
                req.CookieContainer   = new CookieContainer();
                req.AllowAutoRedirect = false;

                using (var res = req.GetRequestStream())
                {
                    byte[] postData = Encoding.UTF8.GetBytes(str);
                    res.Write(postData, 0, postData.Length);
                }

                using (var res = (HttpWebResponse)req.GetResponse())
                {
                    return(res.Cookies["FedAuth"].Value);
                }
            }
        }
        protected override void ProcessRecord()
        {
            base.ProcessRecord();
            WriteVerbose("Process record");

            string connectionPassword;
            string connectionUsername;

            switch (this.ParameterSetName)
            {
            case "Securestring":
            {
                connectionPassword = password;
                connectionUsername = securePassword.ToUnsecureString();
                break;
            }

            case "Credentials":
            {
                connectionPassword = credentials.Password.ToUnsecureString();
                connectionUsername = credentials.UserName;
                break;
            }

            default:
            {
                connectionPassword = password;
                connectionUsername = username;
                break;
            }
            }

            string serverUrl = string.Format("{0}://{1}{2}", requestProtocol, adfsServer, adfsRequestUrl);

            try
            {
                var factory = new WSTrustChannelFactory(new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential), new EndpointAddress(serverUrl))
                {
                    TrustVersion = TrustVersion.WSTrust13
                };
                factory.Credentials.UserName.UserName = connectionUsername;
                factory.Credentials.UserName.Password = connectionPassword;
                var rst = new RequestSecurityToken
                {
                    RequestType = WSTrust13Constants.RequestTypes.Issue,
                    AppliesTo   = new EndpointAddress(adfsAudience),
                    KeyType     = WSTrust13Constants.KeyTypes.Bearer
                };

                var channel      = factory.CreateChannel();
                var genericToken = channel.Issue(rst) as GenericXmlSecurityToken;

                if (outputFormat.ToLower() == "xmltoken")
                {
                    WriteObject(genericToken.TokenXml.OuterXml);
                }
                else if (outputFormat.ToLower() == "samltoken")
                {
                    var tokenHandler = System.IdentityModel.Tokens.SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection();
                    var tokenString  = genericToken.TokenXml.OuterXml;
                    WriteObject(tokenHandler.ReadToken(new XmlTextReader(new StringReader(tokenString))));
                }
                else
                {
                    XmlDocument xmlDocument = new XmlDocument();
                    xmlDocument.LoadXml(genericToken.TokenXml.OuterXml);
                    WriteObject(xmlDocument);
                }
            }
            catch (Exception ex)
            {
                WriteError(new ErrorRecord(new SecurityException(ex.Message), "100", ErrorCategory.AuthenticationError, null));
            }
        }
Beispiel #8
0
        private static SecurityToken ConvertToToken(string xml)
        {
            WS2007FederationHttpBinding binding = new WS2007FederationHttpBinding(WSFederationHttpSecurityMode.TransportWithMessageCredential,
                                                                                  false);

            Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannelFactory factory = new Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannelFactory(binding, new EndpointAddress("https://null-EndPoint"));
            factory.TrustVersion = TrustVersion.WSTrustFeb2005;

            Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannel trustChannel = (Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannel)factory.CreateChannel();

            RequestSecurityTokenResponse response = trustChannel.WSTrustResponseSerializer.CreateInstance();

            response.RequestedSecurityToken = new RequestedSecurityToken(LoadXml(xml).DocumentElement);
            response.IsFinal = true;

            RequestSecurityToken requestToken = new RequestSecurityToken(WSTrustFeb2005Constants.RequestTypes.Issue);

            requestToken.KeyType = WSTrustFeb2005Constants.KeyTypes.Symmetric;

            return(trustChannel.GetTokenFromResponse(requestToken, response));
        }
Beispiel #9
0
        public static SecurityToken getToken(sts.Token token)
        {
            var textmessageEncoding = new TextMessageEncodingBindingElement();

            textmessageEncoding.WriteEncoding  = Encoding.UTF8;
            textmessageEncoding.MessageVersion = MessageVersion.Soap12WSAddressing10;

            var messageSecurity = new AsymmetricSecurityBindingElement();

            messageSecurity.AllowSerializedSigningTokenOnReply = true;
            messageSecurity.MessageSecurityVersion             = MessageSecurityVersion.WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10;
            messageSecurity.MessageSecurityVersion             = MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
            //messageSecurity.EnableUnsecuredResponse = true;
            messageSecurity.IncludeTimestamp                   = false;
            messageSecurity.DefaultAlgorithmSuite              = SecurityAlgorithmSuite.Basic128Rsa15;
            messageSecurity.SecurityHeaderLayout               = SecurityHeaderLayout.Lax;
            messageSecurity.MessageProtectionOrder             = MessageProtectionOrder.SignBeforeEncrypt;
            messageSecurity.LocalClientSettings.DetectReplays  = false;
            messageSecurity.LocalServiceSettings.DetectReplays = false;

            var x509SecurityParamter = new X509SecurityTokenParameters(X509KeyIdentifierClauseType.RawDataKeyIdentifier, SecurityTokenInclusionMode.AlwaysToInitiator);

            messageSecurity.RecipientTokenParameters = x509SecurityParamter;
            messageSecurity.RecipientTokenParameters.RequireDerivedKeys = false;

            var initiator = new X509SecurityTokenParameters(X509KeyIdentifierClauseType.RawDataKeyIdentifier, SecurityTokenInclusionMode.AlwaysToRecipient);

            initiator.RequireDerivedKeys             = false;
            messageSecurity.InitiatorTokenParameters = initiator;

            var binding = new CustomBinding(messageSecurity, textmessageEncoding, new StrippingChannelBindingElement(), new HttpTransportBindingElement());

            Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannelFactory trustChannelFactory = new Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannelFactory(binding, new EndpointAddress(new Uri("http://login.staging.rapidsoft.ru:80/auth/sts"), EndpointIdentity.CreateDnsIdentity("test")));
            trustChannelFactory.Credentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindByIssuerName, "test");
            trustChannelFactory.Credentials.ServiceCertificate.SetDefaultCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindByIssuerName, "test");
            trustChannelFactory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
            trustChannelFactory.Credentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindByIssuerName, "test");
            trustChannelFactory.Endpoint.Contract.ProtectionLevel = ProtectionLevel.None;
            trustChannelFactory.TrustVersion = System.ServiceModel.Security.TrustVersion.WSTrust13;

            Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannel channel = (Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannel)trustChannelFactory.CreateChannel();

            RequestSecurityToken rst = new RequestSecurityToken(RequestTypes.Issue);

            rst.OnBehalfOf = new Microsoft.IdentityModel.Tokens.SecurityTokenElement(token, new Microsoft.IdentityModel.Tokens.SecurityTokenHandlerCollection());
            rst.KeyType    = WSTrust13Constants.KeyTypes.Asymmetric;

            RequestSecurityTokenResponse rstr = null;
            SecurityToken SecurityToken       = channel.Issue(rst, out rstr);

            return(SecurityToken);
        }