Exemplo n.º 1
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));
        }
Exemplo n.º 2
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);
        }
Exemplo n.º 3
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);
            }
Exemplo n.º 4
0
        private GenericXmlSecurityToken RequestTrustToken(string userName, string password, Uri appliesToUrl)
        {
            WSTrustChannel channel = null;

            try
            {
                channel = CreateWSTrustChannel(userName, password);

                var request = new RequestSecurityToken(RequestTypes.Issue)
                {
                    AppliesTo = new EndpointReference(appliesToUrl.OriginalString)
                };
                RequestSecurityTokenResponse response;
                return(channel.Issue(request, out response) as GenericXmlSecurityToken);
            }
            catch
            {
                if ((channel != null) && (channel.State == CommunicationState.Faulted))
                {
                    channel.Abort();
                }
                throw;
            }
            finally
            {
                if ((channel != null) && (channel.State != CommunicationState.Faulted))
                {
                    channel.Close();
                }
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Issues the token
        /// Mostly copied from Service References
        /// </summary>
        private GenericXmlSecurityToken IssueToken()
        {
            _logger.WriteDebug("Issue Token");
            var issuerEndpoint = FindIssuerEndpoint();

            var requestSecurityToken = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                AppliesTo   = new EndpointReference(_infoShareWSAppliesTo.Value.AbsoluteUri),
                KeyType     = System.IdentityModel.Protocols.WSTrust.KeyTypes.Symmetric
            };

            using (var factory = new WSTrustChannelFactory((WS2007HttpBinding)issuerEndpoint.Binding, issuerEndpoint.Address))
            {
                ApplyCredentials(factory.Credentials);
                ApplyTimeout(factory.Endpoint, _connectionParameters.IssueTimeout);

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

                WSTrustChannel channel = null;
                try
                {
                    _logger.WriteDebug($"Issue Token for AppliesTo[{requestSecurityToken.AppliesTo.Uri}]");
                    channel = (WSTrustChannel)factory.CreateChannel();
                    RequestSecurityTokenResponse requestSecurityTokenResponse;
                    return(channel.Issue(requestSecurityToken, out requestSecurityTokenResponse) as GenericXmlSecurityToken);
                }
                catch
                {
                    // Fallback to 10.0.X and 11.0.X configuration using relying party per url like /InfoShareWS/API25/Application.svc
                    requestSecurityToken.AppliesTo = new EndpointReference(_serviceUriByServiceName[Application25].AbsoluteUri);
                    _logger.WriteDebug($"Issue Token for AppliesTo[{requestSecurityToken.AppliesTo.Uri}] as fallback on 10.0.x/11.0.x");
                    RequestSecurityTokenResponse requestSecurityTokenResponse;
                    return(channel.Issue(requestSecurityToken, out requestSecurityTokenResponse) as GenericXmlSecurityToken);
                }
                finally
                {
                    if (channel != null)
                    {
                        channel.Abort();
                    }
                    factory.Abort();
                }
            }
        }
Exemplo n.º 6
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());
            WSTrustChannelFactory trustChannelFactory = new 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;

            WSTrustChannel channel = (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);
        }
Exemplo n.º 7
0
        public SecurityToken GetSecurityToken()
        {
            //service identifier whitin the ADFS server where I want to access, must be configured as RP in ADFS
            //this is the same value we configure on server side for the parameter audienceUris
            EndpointReference serviceAddress = new EndpointReference(@"http://testWCFService.gianlucb.local");

            //who gives me the token
            string stsAddress;

            //ignores certificates error
            ServicePointManager.ServerCertificateValidationCallback = (x, y, z, w) => true;

            //USERNAME
            stsAddress = @"https://sts.gianlucb.local/adfs/services/trust/13/usernamemixed";
            WS2007HttpBinding stsBinding = new WS2007HttpBinding(SecurityMode.TransportWithMessageCredential);

            stsBinding.Security.Transport.ClientCredentialType   = HttpClientCredentialType.Ntlm;
            stsBinding.Security.Message.ClientCredentialType     = MessageCredentialType.UserName;
            stsBinding.Security.Message.EstablishSecurityContext = false;

            WSTrustChannelFactory trustChannelFactory = new WSTrustChannelFactory(stsBinding, stsAddress);

            trustChannelFactory.Credentials.SupportInteractive = false;
            trustChannelFactory.Credentials.UserName.Password  = "******";
            trustChannelFactory.Credentials.UserName.UserName  = "******";

            //---------------------

            //connection
            WSTrustChannel channel = (WSTrustChannel)trustChannelFactory.CreateChannel();

            RequestSecurityToken rst = new RequestSecurityToken(RequestTypes.Issue);

            rst.AppliesTo = serviceAddress;
            rst.KeyType   = KeyTypes.Symmetric;

            RequestSecurityTokenResponse rstr = null;
            SecurityToken token            = channel.Issue(rst, out rstr);
            var           xmlSecurityToken = token as GenericXmlSecurityToken;

            Trace.WriteLine("Received the token:");
            Trace.WriteLine(xmlSecurityToken.TokenXml.InnerXml);

            return(token);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Issues the token
        /// Mostly copied from Service References
        /// </summary>
        public void IssueToken()
        {
            var requestSecurityToken = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                AppliesTo   = new EndpointReference(uris["Application25"].AbsoluteUri),
                KeyType     = System.IdentityModel.Protocols.WSTrust.KeyTypes.Symmetric,
            };

            requestSecurityToken.TokenType = SamlSecurityTokenHandler.Assertion;
            //This should have worked directly but I don't know why it doesn't.
            //using (var factory = new WSTrustChannelFactory(this.issuerServiceEndpoint))
            using (var factory = new WSTrustChannelFactory((WS2007HttpBinding)this.issuerServiceEndpoint.Binding, this.issuerServiceEndpoint.Address))
            {
                ApplyCredentials(factory.Credentials);

                //Apply the connection timeout to the token issue process
                ApplyTimeout(factory.Endpoint, IssueTimeout);

                factory.TrustVersion = TrustVersion.WSTrust13;
                factory.Credentials.SupportInteractive = false;
                WSTrustChannel channel = null;

                try
                {
                    channel = (WSTrustChannel)factory.CreateChannel();
                    RequestSecurityTokenResponse requestSecurityTokenResponse;
                    this.issuedToken = channel.Issue(requestSecurityToken, out requestSecurityTokenResponse) as GenericXmlSecurityToken;
                }
                catch (Exception ex)
                {
                    throw;
                }
                finally
                {
                    if (channel != null)
                    {
                        channel.Abort();
                    }

                    factory.Abort();
                }
            }
        }
        private static SecurityToken GetSamlToken(string realm, string stsEndpoint, ClientCredentials clientCredentials)
        {
            using (var factory = new WSTrustChannelFactory(
                       new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                       new EndpointAddress(new Uri(stsEndpoint))))
            {
                factory.Credentials.UserName.UserName = clientCredentials.UserName.UserName;
                factory.Credentials.UserName.Password = clientCredentials.UserName.Password;
                factory.TrustVersion = TrustVersion.WSTrust13;

                WSTrustChannel channel = null;

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

                    channel = (WSTrustChannel)factory.CreateChannel();

                    RequestSecurityTokenResponse response;
                    var token = channel.Issue(rst, out response);

                    return(token);
                }
                finally
                {
                    if (channel != null)
                    {
                        channel.Abort();
                    }

                    factory.Abort();
                }
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Uses the WSTrustChannel to retrieve an issued token from the STS.
        /// </summary>
        /// <returns>The SecurityToken issued by the STS.</returns>
        private static SecurityToken GetIssuedToken()
        {
            //
            // Note that the default trust version used by the WSTrustChannel
            // is the trust version found on any security binding element in the
            // WSTrustChannelFactory's binding.
            //
            // However, set the TrustVersion property directly on the WSTrustChannelFactory
            // to be explicit.
            //
            WSTrustChannelFactory trustChannelFactory = new WSTrustChannelFactory(GetSecurityTokenServiceBinding(), new EndpointAddress(STSAddress));

            trustChannelFactory.TrustVersion = TrustVersion.WSTrust13;

            WSTrustChannel channel = null;

            try
            {
                //
                // Instantiate the RST object used for the issue request
                // to the STS.
                //
                // To use the February 2005 spec:
                //
                //  RequestSecurityToken rst = new RequestSecurityToken( WSTrustFeb2005Constants.RequestTypes.Issue );
                //
                RequestSecurityToken rst = new RequestSecurityToken(WSTrust13Constants.RequestTypes.Issue);
                rst.AppliesTo = new EndpointAddress(ServiceAddress);

                // Set client entropy, protect with STS's cert.
                // It is not necessary to encrypt the entropy as the message body is encrypted.
                // This sample shows how to encrypt the entropy for scenarios where it is required.
                rst.Entropy = new Entropy(CreateEntropy(), new X509EncryptingCredentials(STSCertificate));

                // Set key type to symmetric.
                rst.KeyType = KeyTypes.Symmetric;

                // Set key size for the symmetric proof key.
                rst.KeySizeInBits = 256;

                //
                // Sends the RST message to the STS and extracts the
                // issued security token in accordance with the WS-Trust
                // specification.
                //
                channel = (WSTrustChannel)trustChannelFactory.CreateChannel();

                SecurityToken token = channel.Issue(rst);

                ((IChannel)channel).Close();
                channel = null;

                trustChannelFactory.Close();
                trustChannelFactory = null;

                return(token);
            }
            finally
            {
                if (channel != null)
                {
                    ((IChannel)channel).Abort();
                }

                if (trustChannelFactory != null)
                {
                    trustChannelFactory.Abort();
                }
            }
        }