Пример #1
0
        /// <summary>
        /// Create the communication channel to the SIMS security server.
        /// Instead of relying on unweildy .config files full of WCF binding information, we will do this longhand as an example.
        /// </summary>
        /// <returns>A channel factory configured with WS2007HttpBinding</returns>
        private WSTrustChannelFactory GetTrustChannelFactory()
        {
            // Use WS2007HttpBinding
            WS2007HttpBinding binding = new WS2007HttpBinding();

            // Timeout settings etc
            binding.CloseTimeout = new TimeSpan(0, 10, 0);
            binding.OpenTimeout  = new TimeSpan(0, 10, 0);
            binding.SendTimeout  = new TimeSpan(0, 10, 0);
            // Quotas
            binding.ReaderQuotas.MaxArrayLength         = 2147483647;
            binding.ReaderQuotas.MaxStringContentLength = 2147483647;
            binding.ReaderQuotas.MaxDepth  = int.MaxValue;
            binding.MaxReceivedMessageSize = int.MaxValue;

            // SSL security mode
            binding.Security.Mode = SecurityMode.TransportWithMessageCredential;

            // The credentials we will pass will be username/password
            binding.Security.Message.ClientCredentialType       = MessageCredentialType.UserName;
            binding.Security.Message.EstablishSecurityContext   = false;
            binding.Security.Message.NegotiateServiceCredential = true;

            binding.UseDefaultWebProxy = true;
            binding.BypassProxyOnLocal = false;

            EndpointAddress endpointAddress = new EndpointAddress(new Uri(_securityServerAddress));

            WSTrustChannelFactory channelFactory = new WSTrustChannelFactory(binding, endpointAddress);

            return(channelFactory);
        }
Пример #2
0
        private static SecurityToken GetToken()
        {
            string stsEndpoint = "https://win-beju5ai4tp7.pbdev.codit.eu/adfs/services/trust/2005/windowstransport";
            // Windows authentication over transport security
            var factory = new WSTrustChannelFactory(
                new WindowsWSTrustBinding(SecurityMode.Transport),
                stsEndpoint);
            factory.TrustVersion = TrustVersion.WSTrustFeb2005;

            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                AppliesTo = new EndpointAddress("https://localhost:8732/ClaimsEnumeratorService/"),
                KeyType = KeyTypes.Symmetric
            };

            var channel = factory.CreateChannel();
            SecurityToken tk = channel.Issue(rst);

            Console.WriteLine(tk.Id);
            foreach (var key in tk.SecurityKeys)
            {
                Console.WriteLine(key.KeySize.ToString());
            }
            Console.WriteLine(tk.ValidFrom);
            Console.WriteLine(tk.ValidTo);

            return tk;
        }
Пример #3
0
    static void Main(String[] arguments)
    {
        if (2 != arguments.Length)
        {
            ShowUsage();
            return;
        }
        String userName = arguments[0];
        String password = arguments[1];

        var serviceAddress = "http://127.0.0.1:450/TimeService.svc";

        var factory = new WSTrustChannelFactory("issuer");
        factory.Credentials.UserName.UserName = userName;
        factory.Credentials.UserName.Password = password;
        var channel = factory.CreateChannel() as WSTrustChannel;
        var rst = new RequestSecurityToken("http://schemas.microsoft.com/idfx/requesttype/issue");

        rst.AppliesTo = new EndpointAddress(serviceAddress);

        RequestSecurityTokenResponse rstr = null;

        Console.WriteLine("Before issue");
        var token = channel.Issue(rst, out rstr);

        Console.WriteLine("After issue");
    }
Пример #4
0
        private SecurityToken GetActAsToken()
        {
            // Retrieve the token that was saved during initial user login
            BootstrapContext bootstrapContext = ClaimsPrincipal.Current.Identities.First().BootstrapContext as BootstrapContext;

            // Use the Thinktecture-implementation of the UserNameWSBinding to setup the channel factory to ADFS
            var binding = new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential);
            var factory = new WSTrustChannelFactory(binding, new EndpointAddress("https://[ADFS]/adfs/services/trust/13/usernamemixed"));

            // For demo purposes, we're authenticating to ADFS using a user name and password representing the web application
            // If the web server is domain-joined, you can use Windows Authentication instead
            factory.Credentials.UserName.UserName = "******";
            factory.Credentials.UserName.Password = "******";

            factory.TrustVersion = TrustVersion.WSTrust13;

            // Setup the request details to ask for a token for the backend service, acting as the logged in user
            var request = new RequestSecurityToken();

            request.RequestType = Thinktecture.IdentityModel.Constants.WSTrust13Constants.RequestTypes.Issue;
            request.AppliesTo   = new EndpointReference("https://[BackendService]/Service.svc");
            request.ActAs       = new SecurityTokenElement(bootstrapContext.SecurityToken);

            // Create the channel
            var channel = factory.CreateChannel();
            RequestSecurityTokenResponse response = null;
            SecurityToken delegatedToken          = channel.Issue(request, out response);

            // Return the acquired token
            return(delegatedToken);
        }
Пример #5
0
        internal bool Logoff(string userName, string password, SecurityToken sessionToken)
        {
            using (WSTrustChannelFactory factory = GetTrustChannelFactory())
            {
                //// Set up credentials
                if (factory.Credentials == null)
                {
                    throw new Exception("Credentails are null");
                }
                factory.Credentials.UserName.UserName  = userName;
                factory.Credentials.UserName.Password  = password;
                factory.Credentials.SupportInteractive = false;

                // Create a "request for token" SOAP message.
                // We want the security server to Issue us with a token
                RequestSecurityToken rst = new RequestSecurityToken(RequestTypes.Cancel);
                // the token we want to cancel
                rst.CancelTarget = new SecurityTokenElement(sessionToken);


                // Create the communicaiton channel
                IWSTrustChannelContract channel = factory.CreateChannel();

                // Cancel token
                // ReSharper disable once UnusedVariable
                RequestSecurityTokenResponse response = channel.Cancel(rst);
                return(response.RequestedTokenCancelled);
            }
        }
    public string AuthenticateUser(string username, string password)
    {
        var binding = new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential)
        {
            ClientCredentialType = HttpClientCredentialType.None
        };
        var trustChannelFactory = new WSTrustChannelFactory(binding, new EndpointAddress(stsEndpointAddress))
        {
            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(RequestTypes.Issue, KeyTypes.Bearer)
        {
            AppliesTo = new EndpointReference(relyingPartyAddress),
            ReplyTo   = relyingPartyAddress,
            TokenType = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0"
        };
        // to some token-related stuff (like transformations etc...)
    }
Пример #7
0
        private WSTrustChannel CreateWSTrustChannel(string username, string password)
        {
            var binding = new WS2007HttpBinding(SecurityMode.Message);

            binding.Security.Message.ClientCredentialType       = MessageCredentialType.UserName;
            binding.Security.Message.NegotiateServiceCredential = true;
            binding.Security.Message.EstablishSecurityContext   = false;

            var timeSpan = new TimeSpan(0, 5, 0);

            binding.SendTimeout    = timeSpan;
            binding.ReceiveTimeout = timeSpan;
            binding.OpenTimeout    = timeSpan;
            binding.CloseTimeout   = timeSpan;

            EndpointIdentity identity = EndpointIdentity.CreateDnsIdentity(_tokenClientOptions.CertificateDnsIdentity);
            var address = new EndpointAddress(_tokenClientOptions.TokenServiceUri, identity);

            var factory = new WSTrustChannelFactory(binding, address);

            if (factory.Credentials == null)
            {
                throw new NullReferenceException(nameof(WSTrustChannelFactory.Credentials));
            }

            factory.TrustVersion = TrustVersion.WSTrust13;
            factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.PeerOrChainTrust;
            factory.Credentials.ServiceCertificate.Authentication.RevocationMode            = X509RevocationMode.NoCheck;
            factory.Credentials.SupportInteractive = false;
            factory.Credentials.UserName.UserName  = username;
            factory.Credentials.UserName.Password  = password;

            return((WSTrustChannel)factory.CreateChannel());
        }
Пример #8
0
        private SecurityToken GetActAsToken()
        {
            // Retrieve the token that was saved during initial user login
            BootstrapContext bootstrapContext = ClaimsPrincipal.Current.Identities.First().BootstrapContext as BootstrapContext;

            // Use the Thinktecture-implementation of the UserNameWSBinding to setup the channel factory to ADFS
            var binding = new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential);
            var factory = new WSTrustChannelFactory(binding, new EndpointAddress("https://[ADFS]/adfs/services/trust/13/usernamemixed"));

            // For demo purposes, we're authenticating to ADFS using a user name and password representing the web application
            // If the web server is domain-joined, you can use Windows Authentication instead
            factory.Credentials.UserName.UserName = "******";
            factory.Credentials.UserName.Password = "******";

            factory.TrustVersion = TrustVersion.WSTrust13;

            // Setup the request details to ask for a token for the backend service, acting as the logged in user
            var request = new RequestSecurityToken();
            request.RequestType = Thinktecture.IdentityModel.Constants.WSTrust13Constants.RequestTypes.Issue;
            request.AppliesTo = new EndpointReference("https://[BackendService]/Service.svc");
            request.ActAs = new SecurityTokenElement(bootstrapContext.SecurityToken);

            // Create the channel
            var channel = factory.CreateChannel();
            RequestSecurityTokenResponse response = null;
            SecurityToken delegatedToken = channel.Issue(request, out response);

            // Return the acquired token
            return delegatedToken;
        }
Пример #9
0
        private static Tuple <string, byte[]> GetToken()
        {
            var binding = new WS2007HttpBinding(SecurityMode.Message);

            binding.Security.Message.ClientCredentialType       = MessageCredentialType.UserName;
            binding.Security.Message.NegotiateServiceCredential = true;
            binding.Security.Message.EstablishSecurityContext   = false;

            var address = new EndpointAddress(new Uri(@"http://localhost:6000/MySTS"),
                                              new DnsEndpointIdentity("MySTS"));

            WSTrustChannelFactory factory = new WSTrustChannelFactory(binding, address);

            factory.TrustVersion = TrustVersion.WSTrust13;

            factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode =
                X509CertificateValidationMode.None;
            factory.Credentials.ServiceCertificate.Authentication.RevocationMode = X509RevocationMode.NoCheck;
            factory.Credentials.UserName.UserName = "******";
            factory.Credentials.UserName.Password = "******"; // got to be same as user name in our example

            WSTrustChannel channel = (WSTrustChannel)factory.CreateChannel();

            var request = new RequestSecurityToken(System.IdentityModel.Protocols.WSTrust.RequestTypes.Issue)
            {
                AppliesTo = new EndpointReference("http://my-server.com")
            };

            RequestSecurityTokenResponse response = null;
            var token = channel.Issue(request, out response) as GenericXmlSecurityToken;

            var proofKey = response.RequestedProofToken.ProtectedKey.GetKeyBytes();

            return(new Tuple <string, byte[]>(token.TokenXml.OuterXml, proofKey));
        }
Пример #10
0
        private WSTrustChannelFactory GetTrustChannelFactory(string securityServerURL)
        {
            WS2007HttpBinding binding = new WS2007HttpBinding
            {
                CloseTimeout = new TimeSpan(0, 10, 0),
                OpenTimeout  = new TimeSpan(0, 10, 0),
                SendTimeout  = new TimeSpan(0, 10, 0),
                ReaderQuotas =
                {
                    MaxArrayLength         = 2147483647,
                    MaxStringContentLength = 2147483647,
                    MaxDepth               = int.MaxValue
                },
                MaxReceivedMessageSize = int.MaxValue,
                Security =
                {
                    Mode    = SecurityMode.TransportWithMessageCredential,
                    Message =
                    {
                        ClientCredentialType       = MessageCredentialType.UserName,
                        EstablishSecurityContext   = false,
                        NegotiateServiceCredential = true
                    }
                },
                UseDefaultWebProxy = true,
                BypassProxyOnLocal = false
            };

            EndpointAddress endpointAddress = new EndpointAddress(new Uri(securityServerURL));

            WSTrustChannelFactory channelFactory = new WSTrustChannelFactory(binding, endpointAddress);

            return(channelFactory);
        }
Пример #11
0
        private void AuthInSts(string userName, string userPassword)
        {
            ServicePointManager.ServerCertificateValidationCallback =
                ((sender, certificate, chain, sslPolicyErrors) => true);
            var rst = new RequestSecurityToken(RequestTypes.Issue);

            rst.AppliesTo = new EndpointReference("https://RelyingParty/*");
            rst.KeyType   = KeyTypes.Bearer;

            using (var trustChannelFactory = new WSTrustChannelFactory("WS2007HttpBinding_IWSTrust13Sync"))
            {
                trustChannelFactory.Credentials.UserName.UserName = userName;
                trustChannelFactory.Credentials.UserName.Password = userPassword;

                var channel = (WSTrustChannel)trustChannelFactory.CreateChannel();
                try
                {
                    _authToken = channel.Issue(rst);
                }
                catch (MessageSecurityException ex)
                {
                    channel.Abort();
                    throw new SecurityTokenException(ex.InnerException.Message, ex);
                }
                UserIdenity = CreateUserIdentityFromSecurityToken(_authToken);
            }
        }
Пример #12
0
        static void Main(string[] args) {

            string idpAddress = "https://idp.contoso.com/SecurityTokenService/Issue.svc/mixed/username";
            string fedAddress = "https://sts.contoso.com/adfs/services/trust/13/IssuedTokenMixedSymmetricBasic256";
            string svcAddress = "https://internalcrm.contoso.com";

            var idpBinding = new UserNameWSTrustBinding() {
                SecurityMode = SecurityMode.TransportWithMessageCredential
            };
            var fedBinding = new IssuedTokenWSTrustBinding(idpBinding, new EndpointAddress(idpAddress)) {
                SecurityMode = SecurityMode.TransportWithMessageCredential,
                //KeyType = SecurityKeyType.SymmetricKey
            };
            var channelFactory = new WSTrustChannelFactory(fedBinding, fedAddress);
            channelFactory.Credentials.UserName.UserName = "******";
            channelFactory.Credentials.UserName.Password = "******";
            var request = new RequestSecurityToken {
                RequestType = RequestTypes.Issue,
                AppliesTo = new EndpointReference(svcAddress),
                //TokenType = Microsoft.IdentityModel.Tokens.SecurityTokenTypes.Saml2TokenProfile11,
                //TokenType = SecurityTokenTypes.Saml,
            };
            var token = channelFactory.CreateChannel().Issue(request);
            //return token;
        }
Пример #13
0
        private SecurityToken RequestFederationToken(GenericXmlSecurityToken xmlToken, string appliesTo)
        {
            var adfsEndpoint = _configuration.AdfsIntegration.FederationEndpoint;

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

            var binding = new IssuedTokenWSTrustBinding();

            binding.SecurityMode = SecurityMode.TransportWithMessageCredential;

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

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

            var channel = factory.CreateChannelWithIssuedToken(xmlToken);

            return(channel.Issue(rst));
        }
Пример #14
0
        public SecurityToken GetToken()
        {
            // Need this because the server has a self-signed certificate that doesn't pass validation
            ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, errors) => true;

            var factory = new WSTrustChannelFactory(
                new UserNameWsTrustBinding(),
                StsWsTrustEndpoint)
            {
                TrustVersion = TrustVersion.WSTrust13
            };

            factory.Credentials.UserName.UserName = UserName;
            factory.Credentials.UserName.Password = Password;

            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                KeyType     = KeyTypes.Bearer,
                TokenType   = "urn:ietf:params:oauth:token-type:jwt",
                AppliesTo   = new EndpointReference(Realm)
            };

            var genericToken = factory.CreateChannel().Issue(rst) as GenericXmlSecurityToken;
            var tokenXml     = genericToken.TokenXml.OuterXml;
            var handler      = new JwtSecurityTokenHandler();
            var token        = handler.ReadToken(new XmlTextReader(new StringReader(tokenXml)));

            TokenHelpers.TokenHelpers.Print(tokenXml);
            Print(token);
            SetPrincipal((JwtSecurityToken)token);
            TokenHelpers.TokenHelpers.PrintCurrentPrincipal();

            return(token);
        }
Пример #15
0
            private SecurityToken CreateChannelAndFetchToken(WSTrustChannelFactory trustChannelFactory, out RequestSecurityTokenResponse rstr)
            {
                trustChannelFactory.TrustVersion = TrustVersion.WSTrust13;
                trustChannelFactory.Credentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation;
                SecurityToken        result = null;
                RequestSecurityToken rst    = new RequestSecurityToken
                {
                    RequestType = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue",
                    KeyType     = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Bearer",
                    AppliesTo   = new EndpointReference(this.serviceUri.AbsoluteUri)
                };
                WSTrustChannel wSTrustChannel = (WSTrustChannel)trustChannelFactory.CreateChannel();

                try
                {
                    result = wSTrustChannel.Issue(rst, out rstr);
                    if (wSTrustChannel.State == CommunicationState.Opened || wSTrustChannel.State == CommunicationState.Opening)
                    {
                        wSTrustChannel.Close(TimeSpan.FromSeconds(5.0));
                    }
                }
                finally
                {
                    if (wSTrustChannel.State != CommunicationState.Closed)
                    {
                        wSTrustChannel.Abort();
                    }
                }
                return(result);
            }
        private static string GetWindowsToken(string windowsAuthSiteEndPoint, string realm)
        {
            var identityProviderEndpoint = new EndpointAddress(new Uri(windowsAuthSiteEndPoint + TenantApiUri.WindowsAuthSite));
            var identityProviderBinding = new WS2007HttpBinding(SecurityMode.Transport);
            identityProviderBinding.Security.Message.EstablishSecurityContext = false;
            identityProviderBinding.Security.Message.ClientCredentialType = MessageCredentialType.None;
            identityProviderBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;

            var trustChannelFactory = new WSTrustChannelFactory(identityProviderBinding, identityProviderEndpoint)
            {
                TrustVersion = TrustVersion.WSTrust13,
            };

            trustChannelFactory.Credentials.ServiceCertificate.SslCertificateAuthentication = new X509ServiceCertificateAuthentication() { CertificateValidationMode = X509CertificateValidationMode.None };
            var channel = trustChannelFactory.CreateChannel();

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

            RequestSecurityTokenResponse rstr = null;
            SecurityToken token = null;

            token = channel.Issue(rst, out rstr);
            var tokenString = (token as GenericXmlSecurityToken).TokenXml.InnerText;
            var jwtString = Encoding.UTF8.GetString(Convert.FromBase64String(tokenString));

            return jwtString;
        }
Пример #17
0
 private static void IncreaseTimeout(WSTrustChannelFactory trustChannelFactory)
 {
     trustChannelFactory.Endpoint.Binding.ReceiveTimeout = TimeSpan.FromMinutes(10);
     trustChannelFactory.Endpoint.Binding.SendTimeout    = TimeSpan.FromMinutes(10);
     trustChannelFactory.Endpoint.Binding.OpenTimeout    = TimeSpan.FromMinutes(10);
     trustChannelFactory.Endpoint.Binding.CloseTimeout   = TimeSpan.FromMinutes(10);
 }
Пример #18
0
        private static SecurityToken GetIdentityProviderToken(string tokenType)
        {
            var binding = new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential);

            var factory = new WSTrustChannelFactory(binding, ConfigurationManager.AppSettings["usernamemixedEP"].ToString())
            {
                TrustVersion = TrustVersion.WSTrust13
            };

            factory.Credentials.UserName.Password        = ConfigurationManager.AppSettings["password"].ToString();
            factory.Credentials.UserName.UserName        = ConfigurationManager.AppSettings["username"].ToString();
            factory.Credentials.SupportInteractive       = false;
            factory.Credentials.UseIdentityConfiguration = true;

            var rst = new RequestSecurityToken
            {
                RequestType = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue",
                AppliesTo   = new EndpointReference(ConfigurationManager.AppSettings["usernamemixedAppliesTo"].ToString()),
                KeyType     = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/SymmetricKey",
                TokenType   = tokenType
            };

            var channel = factory.CreateChannel();

            return(channel.Issue(rst));
        }
Пример #19
0
        private WSTrustChannel CreateChannel()
        {
            var stsBinding = CreateStsBinding();

            UpdateStsSettingsFromEnvironment();
            var trustChannelFactory = new WSTrustChannelFactory(stsBinding, ServiceSettings.StsAddress)
            {
                TrustVersion =
                    TrustVersion
                    .WSTrust13
            };

            IncreaseTimeout(trustChannelFactory);
            trustChannelFactory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
            if (UserName.IsNullOrWhiteSpace())
            {
                trustChannelFactory.Credentials.Windows.ClientCredential = Credential;
            }
            else
            {
                trustChannelFactory.Credentials.UserName.UserName = UserName;
                trustChannelFactory.Credentials.UserName.Password = Password;
            }
            trustChannelFactory.Endpoint.Behaviors.Add(new MustUnderstandBehavior(false));
            var channel = (WSTrustChannel)trustChannelFactory.CreateChannel();

            return(channel);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <param name="config"></param>
        /// <param name="withRefreshToken"></param>
        /// <returns></returns>
        public static AccessTokenResponse ProcessAccessTokenRequest(AccessTokenRequest requestMessage, SecurityTokenServiceConfiguration config, Boolean withRefreshToken)
        {
            ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;

            // Call issuer to create token
            WSTrustChannelFactory factory = new WSTrustChannelFactory("issuer");
            // TODO: factory.Credentials.UserName.UserName = requestMessage.Name ?? requestMessage.ClientId;
            // TODO: factory.Credentials.UserName.Password = requestMessage.Password ?? requestMessage.ClientSecret;
            WSTrustChannel issuer = factory.CreateChannel() as WSTrustChannel;
            RequestSecurityToken rst = new RequestSecurityToken(WSTrust13Constants.RequestTypes.Issue);
            rst.AppliesTo = new EndpointAddress("https://wrap.client");
            rst.KeyType = WSTrust13Constants.KeyTypes.Bearer;

            RequestSecurityTokenResponse response = null;
            issuer.Issue(rst, out response);

            WSTrustSerializationContext context = new WSTrustSerializationContext(
                config.SecurityTokenHandlerCollectionManager,
                config.CreateAggregateTokenResolver(),
                config.IssuerTokenResolver);

            // Create response
            var token = response.RequestedSecurityToken.SecurityToken;
            if (null == token)
            {
                using (XmlReader reader = new XmlNodeReader(response.RequestedSecurityToken.SecurityTokenXml))
                {
                    token = FederatedAuthentication.ServiceConfiguration.SecurityTokenHandlers.ReadToken(reader);
                }
                token = ConvertToSimpleWebToken(token, response);
            }

            // Write token
            return WriteToken(token, withRefreshToken);
        }
Пример #21
0
        private static SecurityToken GetRSTSToken(SecurityToken token, string tokenType)
        {
            var binding = new IssuedTokenWSTrustBinding();

            binding.SecurityMode = SecurityMode.TransportWithMessageCredential;

            var issuredTokenEP = ConfigurationManager.AppSettings["issuedtokenEP"].ToString();

            if (issuredTokenEP.ToLower().EndsWith("issuedtokenmixedasymmetricbasic256sha256") ||
                issuredTokenEP.ToLower().EndsWith("issuedtokenmixedsymmetricbasic256sha256"))
            {
                binding.AlgorithmSuite = SecurityAlgorithmSuite.Basic256Sha256;
            }

            var factory = new WSTrustChannelFactory(binding, issuredTokenEP);

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

            var rst = new RequestSecurityToken
            {
                RequestType = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue",
                AppliesTo   = new EndpointReference(ConfigurationManager.AppSettings["issuedtokenAppliesTo"].ToString()),
                KeyType     = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Bearer",
                TokenType   = tokenType,
            };

            var channel = factory.CreateChannelWithIssuedToken(token);

            return(channel.Issue(rst));
        }
Пример #22
0
        /// <summary>
        /// Creates a security token for the service layer.
        /// </summary>
        /// <returns></returns>
        public static SecurityToken CreateSecurityToken(string stsEndpointAddress, string username, string password, string relyingParty)
        {
            var factory = new WSTrustChannelFactory(
                new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                new EndpointAddress(stsEndpointAddress))
            {
                TrustVersion = TrustVersion.WSTrust13
            };

            if (factory.Credentials == null)
            {
                throw new Exception("Bad Factory");
            }

            factory.Credentials.UserName.UserName = username;
            factory.Credentials.UserName.Password = password;

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

            return(factory.CreateChannel().Issue(rst));
        }
        private static string GetWindowsTokenHelper(string windowsAuthSiteEndPoint)
        {
            var identityProviderEndpoint = new EndpointAddress(new Uri(windowsAuthSiteEndPoint + "/wstrust/issue/windowstransport"));
            var identityProviderBinding  = new WS2007HttpBinding(SecurityMode.Transport);

            identityProviderBinding.Security.Message.EstablishSecurityContext = false;
            identityProviderBinding.Security.Message.ClientCredentialType     = MessageCredentialType.None;
            identityProviderBinding.Security.Transport.ClientCredentialType   = HttpClientCredentialType.Windows;

            var trustChannelFactory = new WSTrustChannelFactory(identityProviderBinding, identityProviderEndpoint)
            {
                TrustVersion = TrustVersion.WSTrust13,
            };

            trustChannelFactory.Credentials.ServiceCertificate.SslCertificateAuthentication = new X509ServiceCertificateAuthentication()
            {
                CertificateValidationMode = X509CertificateValidationMode.None
            };
            var channel = trustChannelFactory.CreateChannel();

            var rst = new RequestSecurityToken(RequestTypes.Issue)
            {
                AppliesTo = new EndpointReference("http://azureservices/AdminSite"),
                KeyType   = KeyTypes.Bearer,
            };

            RequestSecurityTokenResponse rstr = null;
            SecurityToken token = null;

            token = channel.Issue(rst, out rstr);
            var tokenString = (token as GenericXmlSecurityToken).TokenXml.InnerText;
            var jwtString   = Encoding.UTF8.GetString(Convert.FromBase64String(tokenString));

            return(jwtString);
        }
Пример #24
0
        /// <summary>
        /// Authenticates with WCF services using user name/password
        /// and receives a token for further communication with the services.
        /// </summary>
        /// <param name="user">User name</param>
        /// <param name="password">Password</param>
        public static ClaimsPrincipal Authenticate(string user, string password)
        {
            try
            {
                var factory = new WSTrustChannelFactory("sts message");
                factory.Credentials.UserName.UserName = user;
                factory.Credentials.UserName.Password = password;
                // TODO: re-enable certificate validation after using a trusted certificate
                factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
                var channel = factory.CreateChannel();
                IssuedToken = channel.Issue(new RequestSecurityToken(RequestTypes.Issue, KeyTypes.Bearer)
                {
                    AppliesTo = new EndpointReference(AudienceUri)
                });

                var identities = GetIdentitiesFromSamlToken(IssuedToken, AudienceUri, true);
                return(new ClaimsPrincipal(identities));
            }
            catch (MessageSecurityException)
            {
                ErrorList currentErrors = new ErrorList(App.Services.GetService <ResourceManager>());
                currentErrors.AddError(ErrorType.Security, Messages.InvalidCredentials);
                currentErrors.Abort(currentErrors.ErrorsText);
            }
            return(null);
        }
Пример #25
0
        private static string GetIdentityToken()
        {
            "Requesting identity token".ConsoleYellow();

            var factory = new WSTrustChannelFactory(
                new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                _idpEndpoint);

            factory.TrustVersion = TrustVersion.WSTrust13;

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

            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                KeyType     = KeyTypes.Bearer,
                /* TokenType = Microsoft.IdentityModel.Tokens.SecurityTokenTypes.Saml2TokenProfile11, */
                AppliesTo = new EndpointReference(Constants.Realm)
            };

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

            return(token.TokenXml.OuterXml);
        }
        private SecurityToken GetActAsToken(BootstrapContext context)
        {
            string stsAddress = "https://identity.thinktecture.com/idsrvsample/issue/wstrust/mixed/username";
            string realm      = FederatedAuthentication.FederationConfiguration.WsFederationConfiguration.Realm;

            var factory = new WSTrustChannelFactory(
                new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                new EndpointAddress(stsAddress));

            factory.TrustVersion = TrustVersion.WSTrust13;

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

            var rst = new RequestSecurityToken
            {
                AppliesTo = new EndpointReference(realm),

                RequestType = RequestTypes.Issue,
                KeyType     = KeyTypes.Bearer,
                ActAs       = new SecurityTokenElement(context.SecurityToken)
            };

            var channel         = factory.CreateChannel();
            var delegationToken = channel.Issue(rst);

            return(delegationToken);
        }
Пример #27
0
        public static SecurityToken GetToken(SecurityToken dobstsToken, string endpointUri, string spRealm)
        {
            // WSTrust call over SSL with credentails sent in the message.
            var binding = new IssuedTokenWSTrustBinding();
            binding.SecurityMode = SecurityMode.TransportWithMessageCredential;

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

            // Request Bearer Token so no keys or encryption required.
            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                AppliesTo = new EndpointAddress(spRealm),
                KeyType = KeyTypes.Bearer
            };

            // Make the request with the DobstsToken.
            factory.ConfigureChannelFactory();
            var channel = factory.CreateChannelWithIssuedToken(dobstsToken);
            return channel.Issue(rst) as GenericXmlSecurityToken;
        }
        public bool ValidateUser(string userId, string password, out SessionSecurityToken sessionToken)
        {
            // authenticate with WS-Trust endpoint
            var factory = new WSTrustChannelFactory(
                new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                new EndpointAddress("https://localhost/ActiveSTS/SecurityTokenService.svc"));

            factory.Credentials.SupportInteractive = false;
            factory.Credentials.UserName.UserName = userId;
            factory.Credentials.UserName.Password = password;

            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                AppliesTo = new EndpointAddress("https://localhost/stsclient/"),
                KeyType = KeyTypes.Bearer,
                TokenType = Microsoft.IdentityModel.Tokens.SecurityTokenTypes.Saml11TokenProfile11,
            };

            var channel = factory.CreateChannel();

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

            // parse token
            var handlers = FederatedAuthentication.ServiceConfiguration.SecurityTokenHandlers;
            var token = handlers.ReadToken(new XmlTextReader(new StringReader(genericToken.TokenXml.OuterXml)));
            var identity = handlers.ValidateToken(token).First();

            // create session token
            sessionToken = new SessionSecurityToken(ClaimsPrincipal.CreateFromIdentity(identity));
            return true;
        }
        private static string RequestIdentityToken()
        {
            "Requesting identity token".ConsoleYellow();

            var factory = new WSTrustChannelFactory(
                new CertificateWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                _idpEndpoint);
            factory.TrustVersion = TrustVersion.WSTrust13;

            factory.Credentials.ClientCertificate.SetCertificate(
                StoreLocation.CurrentUser,
                StoreName.My,
                X509FindType.FindBySubjectDistinguishedName,
                "CN=Client");

            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                KeyType = KeyTypes.Bearer,
                AppliesTo = _acsBaseAddress
            };

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

            return token.TokenXml.OuterXml;
        }
Пример #30
0
        /// <summary>
        /// The get saml token from adfs.
        /// </summary>
        /// <param name="domain">
        /// The domain.
        /// </param>
        /// <param name="username">
        /// The username.
        /// </param>
        /// <param name="password">
        /// The password.
        /// </param>
        /// <returns>
        /// The System.String.
        /// </returns>
        private static string GetSamlTokenFromAdfs(string domain, string username, string password)
        {
            "Requesting identity token".ConsoleYellow();

            var factory =
                new WSTrustChannelFactory(
                    new WindowsWSTrustBinding(SecurityMode.TransportWithMessageCredential), _idpEndpoint);

            factory.TrustVersion = TrustVersion.WSTrust13;
            factory.Credentials.Windows.ClientCredential.Domain   = domain;
            factory.Credentials.Windows.ClientCredential.UserName = username;
            factory.Credentials.Windows.ClientCredential.Password = password;

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

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

            return(token.TokenXml.OuterXml);
        }
Пример #31
0
        private static string GetTokenFromAdfs20()
        {
            var binding = new WS2007HttpBinding(SecurityMode.TransportWithMessageCredential);

            binding.Security.Message.ClientCredentialType       = MessageCredentialType.UserName;
            binding.Security.Message.NegotiateServiceCredential = true;
            binding.Security.Message.EstablishSecurityContext   = false;

            var address = new EndpointAddress(
                new Uri(@"https://yourserver.com/adfs/services/trust/13/usernamemixed"));

            WSTrustChannelFactory factory = new WSTrustChannelFactory(binding, address);

            factory.TrustVersion = TrustVersion.WSTrust13;

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

            WSTrustChannel channel = (WSTrustChannel)factory.CreateChannel();

            var request = new RequestSecurityToken(System.IdentityModel.Protocols.WSTrust.RequestTypes.Issue)
            {
                AppliesTo = new EndpointReference("https://relyingparty"),
                KeyType   = KeyTypes.Bearer
            };

            RequestSecurityTokenResponse response = null;
            var token = channel.Issue(request, out response) as GenericXmlSecurityToken;

            return(token.TokenXml.OuterXml);
        }
Пример #32
0
        public SecurityToken Login(string userName, string password, string schoolId, string tenantId, string applicationServerUrl, string securityServerUrl)
        {
            SecurityToken identityToken;

            using (WSTrustChannelFactory factory = GetTrustChannelFactory(securityServerUrl))
            {
                if (factory.Credentials == null)
                {
                    throw new Exception("Credentails are null");
                }
                factory.Credentials.UserName.UserName  = userName;
                factory.Credentials.UserName.Password  = password;
                factory.Credentials.SupportInteractive = false;

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

                IWSTrustChannelContract channel = factory.CreateChannel();

                RequestSecurityTokenResponse response;
                identityToken = channel.Issue(rst, out response);
            }

            using (WSTrustChannelFactory factory = GetTrustChannelFactory(securityServerUrl))
            {
                if (factory.Credentials == null)
                {
                    throw new Exception("Credentails are null");
                }

                factory.Credentials.UserName.UserName        = userName;
                factory.Credentials.UserName.Password        = password;
                factory.Credentials.SupportInteractive       = false;
                factory.Credentials.UseIdentityConfiguration = true;

                factory.CreateChannelWithIssuedToken(identityToken);

                var channel = factory.CreateChannel();

                var rst = new RequestSecurityToken(
                    RequestTypes.Issue,
                    KeyTypes.Bearer)
                {
                    AdditionalContext = new AdditionalContext()
                };

                rst.AdditionalContext.Items.Add(new ContextItem(new Uri(SimsLoginContextSchoolClaimUrl), schoolId));
                rst.AdditionalContext.Items.Add(new ContextItem(new Uri(SimsLoginContextTenantClaimUrl), tenantId));
                rst.AppliesTo = new EndpointReference(applicationServerUrl);
                rst.ActAs     = new SecurityTokenElement(identityToken);

                RequestSecurityTokenResponse response;
                return(channel.Issue(rst, out response));
            }
        }
Пример #33
0
        protected virtual TokenResponse IssueTokenForRst(WSTrustChannelFactory factory, RequestSecurityToken rst)
        {
            var channel = factory.CreateChannel();
            RequestSecurityTokenResponse rstr;
            var token = channel.Issue(rst, out rstr);

            return(new TokenResponse(token, rstr));
        }
Пример #34
0
        private TokenResponse GetSecurityTokenResponse(string realm, string username, string password)
        {
            Log.Debug(string.Format("Requesting token for {0} at {1} from {2}", username, realm, _usernameMixedEndpoint));
            WSTrustChannelFactory factory = CreateUsernameWSTrustChannelFactory(username, password);
            var rst = CreateRst(realm);

            return(IssueTokenForRst(factory, rst));
        }
Пример #35
0
        public async Task <TokenResponse> GetTokenResponseForCurrentProcessIdentityAsync(string realm)
        {
            Log.Debug(string.Format("Requesting token for current process identity at {0} from {1}", realm, _usernameMixedEndpoint));
            WSTrustChannelFactory factory = CreateWindowsTransportWSTrustChannelFactory();
            var rst = CreateRst(realm);

            return(await IssueTokenForRstAsync(factory, rst).ConfigureAwait(false));
        }
Пример #36
0
        public async Task <TokenResponse> GetSecurityTokenResponseAsync(string realm, string username, string password)
        {
            Log.Debug(string.Format("Requesting token for {0} at {1} from {2}", username, realm, _usernameMixedEndpoint));
            WSTrustChannelFactory factory = CreateUsernameWSTrustChannelFactory(username, password);
            var rst = CreateRst(realm);

            return(await IssueTokenForRstAsync(factory, rst).ConfigureAwait(false));
        }
Пример #37
0
        public static IEnumerable <Claim> Validate(string user, string password)
        {
            string serviceTokenUrl = ConfigurationManager.AppSettings["ADFS_ServiceTokenUrl_usernamemixed"];
            string relyingPartyURL = ConfigurationManager.AppSettings["ADFS_RelyingPartyURL"];


            WSTrustChannelFactory factory = new WSTrustChannelFactory(
                WSTrust13Bindings.UsernameMixed,
                new EndpointAddress(serviceTokenUrl));

            factory.TrustVersion = TrustVersion.WSTrust13;

            RequestSecurityToken rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                KeyType     = KeyTypes.Bearer,
                TokenType   = "urn:oasis:names:tc:SAML:2.0:assertion",
                AppliesTo   = new EndpointReference(relyingPartyURL)
            };


            factory.Credentials.UserName.UserName = user;       // "YOUR_USER_NAME";
            factory.Credentials.UserName.Password = password;   // "***********";

            RequestSecurityTokenResponse rstrr = null;
            SecurityToken issuedToken          = factory.CreateChannel().Issue(rst, out rstrr);


            // Validate the token and get the claims
            RequestSecurityTokenResponse r = factory.CreateChannel().Validate(rst);


            // ??
            var genericToken = issuedToken as GenericXmlSecurityToken;

            FederationConfiguration f = new FederationConfiguration(true);
            var handlers = f.IdentityConfiguration.SecurityTokenHandlerCollectionManager.SecurityTokenHandlerCollections.First();

            var cToken      = handlers.ReadToken(new XmlTextReader(new StringReader(genericToken.TokenXml.OuterXml)));
            var identity    = handlers.ValidateToken(cToken).First();
            var userIdenity = new ClaimsPrincipal(identity);

            Console.WriteLine(userIdenity.Identity.Name);
            Console.WriteLine(userIdenity.Identity.IsAuthenticated);
            foreach (Claim claim in userIdenity.Claims)
            {
                Console.WriteLine("----------------------------------------------");
                Console.WriteLine("Type =" + claim.Type);
                Console.WriteLine("Value =" + claim.Value);
                Console.WriteLine("ValueType =" + claim.ValueType);
                Console.WriteLine("Issuer =" + claim.Issuer);
                Console.WriteLine("OriginalIssuer =" + claim.OriginalIssuer);
                Console.WriteLine("Properties =" + claim.Properties);
                Console.WriteLine("Subject =" + claim.Subject);
            }

            return(userIdenity.Claims);
        }
        public static void tokenTest()
        {
            string relyingPartyId         = "https://shadfs.sanfordhealth.org/adfs/ls/ldpinitiatedsignon.aspx";
            WSTrustChannelFactory factory = null;

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

                factory.TrustVersion = TrustVersion.WSTrust13;

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

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

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

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

                ValidateSamlToken(samlToken2);

                X509Certificate2 certificate = null;

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

                //  var jwt = ConvertSamlToJwt(samlToken2, "https://party.mycomp.com", certificate);
            }
            finally
            {
                if (factory != null)
                {
                    try
                    {
                        factory.Close();
                    }
                    catch (CommunicationObjectFaultedException)
                    {
                        factory.Abort();
                    }
                }
            }
Пример #39
0
        /// <summary>
        /// Requester et security token fra AD FS 2.0 sts'en via
        /// user name authentication
        /// Token'et kan derpå vedhæftes et kald til en service.
        /// Der kan angives
        /// et optionelt ActAs security token. Hvis dette token angives
        /// vil kaldet til STS'en blive et ActAs kald
        /// </summary>
        public static SecurityToken RequestSecurityTokenWithWindowsAuth(
            EndpointAddress stsAddress,
            EndpointAddress serviceAddress,
            string userName = null,
            string password = null)
        {
            // Windows binding og ws-trust 1.3
            var stsBinding = new WindowsWSTrustBinding
            {
                SecurityMode = SecurityMode.Message,
                TrustVersion = TrustVersion.WSTrust13
            };

            // Lav channel factory
            var channelFactory = new WSTrustChannelFactory(
                stsBinding,
                stsAddress);

            if (channelFactory.Credentials == null)
            {
                throw new ApplicationException("ChannelFactory credentials cannot be null");
            }

            if (!string.IsNullOrEmpty(userName))
            {
                // Sæt client credentials til en lokal bruger
                channelFactory.Credentials.Windows.ClientCredential.UserName = userName;
                channelFactory.Credentials.Windows.ClientCredential.Password = password;
                channelFactory.Credentials.UseIdentityConfiguration          = true;
            }


            // Lav channel og brug act as hvis der er et act as token med
            var channel = (WSTrustChannel)channelFactory.CreateChannel();

            try
            {
                // Lav RST med symmetric keys og saml 1.1 token
                var requestSecurityToken = new RequestSecurityToken(RequestTypes.Issue)
                {
                    AppliesTo = new EndpointReference(serviceAddress.ToString()),
                    TokenType = SecurityTokenTypes.Saml11TokenProfile11,
                    KeyType   = KeyTypes.Symmetric
                };

                // Send request (RST) og modtag response (RSTR)
                var securityToken = channel.Issue(requestSecurityToken);

                return(securityToken);
            }
            finally
            {
                CloseChannel(channel);
            }
        }
        private static RequestSecurityTokenResponse RequestToken(RequestSecurityToken rst)
        {
            var factory = new WSTrustChannelFactory(
                new CertificateWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                new EndpointAddress(idp));
            factory.Credentials.ClientCertificate.Certificate = X509Certificates.GetCertificateFromStore("CN=Client");

            RequestSecurityTokenResponse rstr;
            var token = factory.CreateChannel().Issue(rst, out rstr);

            return rstr;
        }
        private static IWSTrustChannelContract CreateWSTrustChannel(EndpointAddress stsAddress, Binding binding, ClientCredentials credentials)
        {
            var factory = new WSTrustChannelFactory(
                binding,
                stsAddress);

            var creds = factory.Endpoint.Behaviors.Find<ClientCredentials>();
            factory.Endpoint.Behaviors.Remove(creds);
            factory.Endpoint.Behaviors.Add(credentials);

            return factory.CreateChannel();
        }
Пример #42
0
        public TokenClient(string configName)
        {
            if (string.IsNullOrEmpty(configName))
            {
                throw new ArgumentNullException("configName");
            }

            _factory = new WSTrustChannelFactory(configName)
            {
                TrustVersion = TrustVersion.WSTrust13
            };
        }
        public static IWSTrustChannelContract CreateMixedUserNameClient(string userName, string password, string endpointAddress)
        {
            var factory = new WSTrustChannelFactory(
                new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                new EndpointAddress(endpointAddress));
            factory.TrustVersion = TrustVersion.WSTrust13;

            factory.Credentials.UserName.UserName = userName;
            factory.Credentials.UserName.Password = password;

            return factory.CreateChannel();
        }
Пример #44
0
        public static SecurityToken GetIssuedToken(Uri audience, X509Certificate2 clientCertificate, X509Certificate2 stsCertificate, Uri endpoint, SecurityToken bootstrapSecurityToken)
        {
            WSTrustChannelFactory trustChannelFactory = new WSTrustChannelFactory(SecureTokenServiceBindings.GetIssuedTokenBindingNonSSL(), new EndpointAddress(endpoint, EndpointIdentity.CreateDnsIdentity("DANID A/S - DanID Test")));
            trustChannelFactory.Credentials.ServiceCertificate.DefaultCertificate = stsCertificate;
            trustChannelFactory.Credentials.ClientCertificate.Certificate = clientCertificate;
            trustChannelFactory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
            trustChannelFactory.Endpoint.Contract.ProtectionLevel = ProtectionLevel.Sign;

            trustChannelFactory.TrustVersion = TrustVersion.WSTrust13;
            var channel = (WSTrustChannel)trustChannelFactory.CreateChannel();
            var rst = RequestSecurityToken(bootstrapSecurityToken, clientCertificate, audience, new List<RequestClaim>());
            var response = channel.Issue(rst);
            return response;
        }
        public static IWSTrustChannelContract CreateMixedCertificateClient(string subjectName, string endpointAddress)
        {
            var factory = new WSTrustChannelFactory(
                new CertificateWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                new EndpointAddress(endpointAddress));
            factory.TrustVersion = TrustVersion.WSTrust13;

            factory.Credentials.ClientCertificate.SetCertificate(
                StoreLocation.CurrentUser,
                StoreName.My,
                X509FindType.FindBySubjectDistinguishedName,
                subjectName);

            return factory.CreateChannel();
        }
Пример #46
0
        private static string GetADFSToken(string windowsAuthSiteEndPoint, string userName, string Password)
        {
            try
            {
                var identityProviderEndpoint = new EndpointAddress(new Uri(windowsAuthSiteEndPoint + "/adfs/services/trust/13/usernamemixed"));
                var identityProviderBinding = new WS2007HttpBinding(SecurityMode.TransportWithMessageCredential);
                identityProviderBinding.Security.Message.EstablishSecurityContext = false;
                identityProviderBinding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
                identityProviderBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;

                var trustChannelFactory = new WSTrustChannelFactory(identityProviderBinding, identityProviderEndpoint)
                {
                    TrustVersion = TrustVersion.WSTrust13,
                };

                trustChannelFactory.Credentials.SupportInteractive = false;
                trustChannelFactory.Credentials.UserName.UserName = userName;
                trustChannelFactory.Credentials.UserName.Password = Password;
                var channel = trustChannelFactory.CreateChannel();
                var rst = new RequestSecurityToken(RequestTypes.Issue)
                {
                    AppliesTo = new EndpointReference("http://azureservices/TenantSite"),
                    TokenType = "urn:ietf:params:oauth:token-type:jwt",
                    KeyType = KeyTypes.Bearer,
                };

                RequestSecurityTokenResponse rstr = null;
                SecurityToken token = null;

                token = channel.Issue(rst, out rstr);
                var tokenString = (token as GenericXmlSecurityToken).TokenXml.InnerText;
                var jwtString = Encoding.UTF8.GetString(Convert.FromBase64String(tokenString));

                return jwtString;
            }
            catch (Exception ex)
            {
                using (EventLog eventLog = new EventLog("Application"))
                {
                    eventLog.Source = "Application";
                    eventLog.WriteEntry("ADFS HealthCheck: " + (object)ex, EventLogEntryType.Error, 1111, (short)1);
                }
                return ex.ToString();
            }
        }
        private static SecurityToken RequestIdentityToken()
        {
            "Requesting identity token".ConsoleYellow();

            var factory = new WSTrustChannelFactory(
                new WindowsWSTrustBinding(SecurityMode.Transport),
                _idpEndpoint);
            factory.TrustVersion = TrustVersion.WSTrust13;

            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                KeyType = KeyTypes.Symmetric,
                AppliesTo = new EndpointAddress("https://" + Constants.WebHost + "/webservicesecurity/")
            };

            return factory.CreateChannel().Issue(rst);
        }
Пример #48
0
        private static SecurityToken RequestToken()
        {
            var factory = new WSTrustChannelFactory(
                new WindowsWSTrustBinding(SecurityMode.Transport),
                new EndpointAddress("https://adfs.leastprivilege.vm/adfs/services/trust/13/windowstransport"));
            factory.TrustVersion = TrustVersion.WSTrust13;

            var channel = factory.CreateChannel();

            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                KeyType = KeyTypes.Bearer,
                AppliesTo = new EndpointReference("https://adfs.leastprivilege.vm/adfsapp/")
            };

            return channel.Issue(rst);
        }
        private static SecurityToken RequestSymmetricEncryptedToken(X509Certificate2 decryptionCert)
        {
            var factory = new WSTrustChannelFactory(
                new CertificateWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                new EndpointAddress(idp));
            factory.Credentials.ClientCertificate.Certificate = X509Certificates.GetCertificateFromStore("CN=Client");

            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                AppliesTo = new EndpointAddress(encryptedRP),
                KeyType = KeyTypes.Symmetric
            };

            var genericToken = factory.CreateChannel().Issue(rst) as GenericXmlSecurityToken;
            var token = genericToken.ToSecurityToken(decryptionCert);

            return token;
        }
Пример #50
0
        private static SecurityToken RequestSamlToken()
        {
            var factory = new WSTrustChannelFactory(
                new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                new EndpointAddress(adfsEndpoint));
            factory.TrustVersion = TrustVersion.WSTrust13;

            factory.Credentials.UserName.UserName = username;
            factory.Credentials.UserName.Password = password;

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

            return factory.CreateChannel().Issue(rst);
        }
        private static string GetIdentityToken()
        {
            "Requesting identity token".ConsoleYellow();

            var factory = new WSTrustChannelFactory(
                new WindowsWSTrustBinding(SecurityMode.Transport),
                _idpEndpoint);
            factory.TrustVersion = TrustVersion.WSTrust13;

            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                KeyType = KeyTypes.Bearer,
                /* TokenType = Microsoft.IdentityModel.Tokens.SecurityTokenTypes.Saml2TokenProfile11, */
                AppliesTo = new EndpointAddress(Constants.Realm)
            };

            var token = factory.CreateChannel().Issue(rst) as GenericXmlSecurityToken;
            return token.TokenXml.OuterXml;
        }
        public GenericXmlSecurityToken RequestToken(string issuer, string appliesTo, RecordsManagerCredentials credentials)
        {
            var binding = (issuer.ToLower().StartsWith("https")) ? this.GetHttpsBinding() : this.GetHttpBinding();

            var address = new EndpointAddress(issuer);

            var factory = new WSTrustChannelFactory(binding, address);
            factory.TrustVersion = TrustVersion.WSTrust13;
            factory.Credentials.Windows.ClientCredential = credentials.GetCredential();

            var channel = factory.CreateChannel();

            var rst = new RequestSecurityToken(RequestTypes.Issue)
            {
                AppliesTo = new EndpointAddress(appliesTo)
            };

            RequestSecurityTokenResponse rstr = null;

            return channel.Issue(rst, out rstr) as GenericXmlSecurityToken;
        }
        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;
        }
        public GenericXmlSecurityToken RequestToken(string username, string password, string relyingPartyId)
        {
            var factory = new WSTrustChannelFactory(
                    new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                     new EndpointAddress(this.ADFSUserNameMixedEndpoint));

            factory.TrustVersion = TrustVersion.WSTrust13;

            factory.Credentials.UserName.UserName = username;
            factory.Credentials.UserName.Password = password;

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

            return genericToken;
        }
Пример #55
0
        public static SecurityToken GetToken(string endpointUri, string username, string password, string realm)
        {
            // use WSTrust and SSL Transport Mode with security credentials being sent with the message.
            var endpoint = new EndpointAddress(endpointUri);
            var factory = new WSTrustChannelFactory(new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential), endpoint);
            factory.TrustVersion = TrustVersion.WSTrust13;

            factory.Credentials.UserName.UserName = username;
            factory.Credentials.UserName.Password = password;

            // Symmetric key request.
            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                AppliesTo = new EndpointAddress(realm),
                KeyType = KeyTypes.Symmetric
            };

            // Token will be encrypted with ADFS Token Signing cert.
            var channel = factory.CreateChannel();
            return channel.Issue(rst);
        }
        public string GetTenantToken(string authSiteEndPoint, string userName, string password, bool validateCertificate, string realm)
        {
            var identityProviderEndpoint = new EndpointAddress(new Uri(authSiteEndPoint + TenantApiUri.AspNetAuthSite));

            var identityProviderBinding = new WS2007HttpBinding(SecurityMode.TransportWithMessageCredential);
            identityProviderBinding.Security.Message.EstablishSecurityContext = false;
            identityProviderBinding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
            identityProviderBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;

            var trustChannelFactory = new WSTrustChannelFactory(identityProviderBinding, identityProviderEndpoint)
            {
                TrustVersion = TrustVersion.WSTrust13,
            };

            if (!validateCertificate)
            {
                trustChannelFactory.Credentials.ServiceCertificate.SslCertificateAuthentication = new X509ServiceCertificateAuthentication() { CertificateValidationMode = X509CertificateValidationMode.None };
            }
            trustChannelFactory.Credentials.SupportInteractive = false;
            trustChannelFactory.Credentials.UserName.UserName = userName;
            trustChannelFactory.Credentials.UserName.Password = password;

            var channel = trustChannelFactory.CreateChannel();
            var rst = new RequestSecurityToken(RequestTypes.Issue)
            {
                AppliesTo = new EndpointReference(realm),
                TokenType = "urn:ietf:params:oauth:token-type:jwt",
                KeyType = KeyTypes.Bearer,
            };

            RequestSecurityTokenResponse rstr = null;
            SecurityToken token = null;

            token = channel.Issue(rst, out rstr);
            var tokenString = (token as GenericXmlSecurityToken).TokenXml.InnerText;
            var jwtString = Encoding.UTF8.GetString(Convert.FromBase64String(tokenString));

            return jwtString;
        }
        private static string GetSamlToken()
        {
            "Requesting identity token".ConsoleYellow();

            var factory = new WSTrustChannelFactory(
                new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                Constants.IdSrv.WSTrustEndpoint);
            factory.TrustVersion = TrustVersion.WSTrust13;

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

            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                KeyType = KeyTypes.Bearer,
                TokenType = TokenTypes.Saml2TokenProfile11,
                AppliesTo = new EndpointReference(Constants.Realm)
            };

            var token = factory.CreateChannel().Issue(rst) as GenericXmlSecurityToken;
            return token.TokenXml.OuterXml;
        }
        private static string GetIdentityToken()
        {
            "Requesting identity token".ConsoleYellow();

            var factory = new WSTrustChannelFactory(
                new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                _idpEndpoint);
            factory.TrustVersion = TrustVersion.WSTrust13;

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

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

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

            return token.TokenXml.OuterXml;
        }
        /// <summary>
        /// Returns Generic XML Security Token from ADFS to generated FedAuth
        /// </summary>
        /// <param name="serialNumber">Serial Number of Certificate from CurrentUSer > My Certificate</param>
        /// <param name="certificateMixed">ADFS Endpoint for Certificate Mixed Authentication</param>
        /// <param name="relyingPartyIdentifier">Identifier of the ADFS relying party that we're hitting</param>
        /// <returns></returns>
        private GenericXmlSecurityToken RequestToken(string serialNumber, Uri certificateMixed, string relyingPartyIdentifier)
        {
            GenericXmlSecurityToken genericToken = null;
            using (var factory = new WSTrustChannelFactory(new CertificateWSTrustBinding(SecurityMode.TransportWithMessageCredential), new EndpointAddress(certificateMixed)))
            {
                
                factory.TrustVersion = TrustVersion.WSTrust13;
                // Hookup the user and password 
                factory.Credentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindBySerialNumber, serialNumber);
                
                var requestSecurityToken = new RequestSecurityToken
                {
                    RequestType = RequestTypes.Issue,
                    AppliesTo = new EndpointReference(relyingPartyIdentifier),
                    KeyType = KeyTypes.Bearer
                };

                IWSTrustChannelContract channel = factory.CreateChannel();
                genericToken = channel.Issue(requestSecurityToken) as GenericXmlSecurityToken;
                factory.Close();
            }
            return genericToken;
        }
Пример #60
0
        private GenericXmlSecurityToken RequestToken(string userName, string passWord, Uri userNameMixed, string relyingPartyIdentifier)
        {
            GenericXmlSecurityToken genericToken = null;
            using (var factory = new WSTrustChannelFactory(new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential), new EndpointAddress(userNameMixed)))
            {
                factory.TrustVersion = TrustVersion.WSTrust13;
                // Hookup the user and password 
                factory.Credentials.UserName.UserName = userName;
                factory.Credentials.UserName.Password = passWord;

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

                IWSTrustChannelContract channel = factory.CreateChannel();
                genericToken = channel.Issue(requestSecurityToken) as GenericXmlSecurityToken;
                factory.Close();
            }
            return genericToken;
        }