Esempio n. 1
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);
            }
        }
Esempio n. 2
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));
            }
        }
        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();
                    }
                }
            }
Esempio n. 4
0
 private SecurityToken GetSecurityToken(IWSTrustChannelContract channel, RequestSecurityToken rst)
 {
     try
     {
         RequestSecurityTokenResponse rstr = null;
         var token = channel.Issue(rst, out rstr);
         return(token);
     }
     catch (Exception ex)
     {
         Logging.Exception(ex);
         Logging.DebugMessage(string.Format("Request: user={0}, stsAddress={1} thumbprint={2}", UserName, ServiceSettings.StsAddress, ThumbprintResolver.ResolveThumbprint(ServiceSettings.Thumbprint, ServiceSettings.IssuerAddress)));
         throw;
     }
 }
Esempio n. 5
0
        /// <summary>
        /// Creates a security token for the service layer.
        /// </summary>
        /// <returns></returns>
        private static SecurityToken CreateSecurityToken(TimeSpan?lifeTime, string user, string password)
        {
            var factory = new WSTrustChannelFactory(
                new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                new EndpointAddress(WsTrustAddress))
            {
                TrustVersion = TrustVersion.WSTrust13
            };

            if (factory.Credentials == null)
            {
                throw new Exception(ErrBadFactory);
            }

            // the identity authorized to 'act as' the current principal
            factory.Credentials.UserName.UserName = user;
            factory.Credentials.UserName.Password = password;

            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                KeyType     = KeyTypes.Bearer,
                AppliesTo   = new EndpointReference(ServiceHostAddress),
                //ActAs = new SecurityTokenElement(bootstrap) //may want to look at using actas in the future.
            };

            if (lifeTime != null)
            {
                Log.Debug("Token lifetime config value found. Setting service token lifetime to {0}", lifeTime);
                rst.Lifetime = new Lifetime(null, DateTime.Now.Add(lifeTime.Value));
            }
            try
            {
                Log.Debug("Creating channel to sts to request ActAs Token. Address:{0}", WsTrustAddress);
                IWSTrustChannelContract channel = factory.CreateChannel();
                Log.Debug("Asking STS to issue ActAs Token. Address:{0}", WsTrustAddress);
                //ask the STS to issue a token for the service
                SecurityToken delegationToken = channel.Issue(rst);
                return(delegationToken);
            }
            catch (Exception ex)
            {
                string msg = "Cannot create service security token.";
                Log.Error("{0} Ex:{1}", msg, ex.GetBaseException().Message);
                throw new Exception(msg);
            }
        }
Esempio n. 6
0
        public void Setup()
        {
            _mixedUserNameClient = WSTrustClientFactory.CreateMixedUserNameClient(
                Constants.Credentials.ValidUserName,
                Constants.Credentials.ValidPassword,
                baseAddressUserName);

            _mixedCertificateClient = WSTrustClientFactory.CreateMixedCertificateClient(
                Constants.Certificates.ValidClientCertificateName,
                baseAddressCertificate);

            _rst = new RequestSecurityToken
            {
                AppliesTo   = new EndpointAddress(rp),
                RequestType = RequestTypes.Issue,
                KeyType     = KeyTypes.Symmetric
            };
        }
        public void Setup()
        {
            _mixedUserNameClient = WSTrustClientFactory.CreateMixedUserNameClient(
                Constants.Credentials.ValidUserName,
                Constants.Credentials.ValidPassword,
                baseAddressUserName);

            _mixedCertificateClient = WSTrustClientFactory.CreateMixedCertificateClient(
                Constants.Certificates.ValidClientCertificateName,
                baseAddressCertificate);

            _rst = new RequestSecurityToken
            {
                AppliesTo = new EndpointReference(rp),
                RequestType = RequestTypes.Issue,
                KeyType = KeyTypes.Symmetric
            };

        }
        /// <summary>
        /// Issues security token
        /// </summary>
        /// <param name="channel">
        /// The channel.
        /// </param>
        /// <param name="serviceAddress">
        /// The service address.
        /// </param>
        /// <param name="actAsToken">
        /// The act as token.
        /// </param>
        /// <param name="onBehalfOf">
        /// the on behalf of token
        /// </param>
        /// <returns>
        /// the security token
        /// </returns>
        public virtual SecurityToken IssueToken(IWSTrustChannelContract channel, string serviceAddress, SecurityToken actAsToken = null, SecurityToken onBehalfOf = null)
        {
            var rst = new RequestSecurityToken(RequestTypes.Issue)
            {
                AppliesTo = new EndpointAddress(serviceAddress)
            };
            if (actAsToken != null)
            {
                rst.ActAs = new SecurityTokenElement(actAsToken);
            }

            if (onBehalfOf != null)
            {
                rst.OnBehalfOf = new SecurityTokenElement(onBehalfOf);
            }

            RequestSecurityTokenResponse rstr;
            return channel.Issue(rst, out rstr);
        }
    /// <summary>
    /// Requests a security token from the ADFS server
    /// </summary>
    /// <param name="username">The username</param>
    /// <param name="password">The password</param>
    /// <param name="endpoint">The ADFS endpoint</param>
    /// <returns></returns>
    public GenericXmlSecurityToken RequestToken(string username, SecureString password, string endpoint)
    {
        WSTrustChannelFactory factory = new WSTrustChannelFactory(
            new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
            new EndpointAddress(adfsUserNameMixedEndpoint));

        factory.TrustVersion = TrustVersion.WSTrust13;
        factory.Credentials.UserName.UserName = username;
        factory.Credentials.UserName.Password = new System.Net.NetworkCredential(string.Empty, password).Password;
        RequestSecurityToken token = new RequestSecurityToken
        {
            RequestType = RequestTypes.Issue,
            AppliesTo   = new EndpointReference(endpoint),
            KeyType     = KeyTypes.Bearer
        };
        IWSTrustChannelContract channel = factory.CreateChannel();

        return(channel.Issue(token) as GenericXmlSecurityToken);
    }
Esempio n. 10
0
        /// <summary>
        /// Returns Generic XML Security Token from ADFS to generated FedAuth
        /// </summary>
        /// <param name="kerberosMixed">ADFS Endpoint for Kerberos Mixed Authentication</param>
        /// <param name="relyingPartyIdentifier">Identifier of the ADFS relying party that we're hitting</param>
        /// <returns></returns>
        private GenericXmlSecurityToken RequestToken(Uri kerberosMixed, string relyingPartyIdentifier)
        {
            GenericXmlSecurityToken genericToken = null;

            using (var factory = new WSTrustChannelFactory(new KerberosWSTrustBinding(SecurityMode.TransportWithMessageCredential), new EndpointAddress(kerberosMixed)))
            {
                factory.TrustVersion = TrustVersion.WSTrust13;
                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);
        }
Esempio n. 11
0
        /// <summary>
        /// Issues security token
        /// </summary>
        /// <param name="channel">
        /// The channel.
        /// </param>
        /// <param name="serviceAddress">
        /// The service address.
        /// </param>
        /// <param name="actAsToken">
        /// The act as token.
        /// </param>
        /// <param name="onBehalfOf">
        /// the on behalf of token
        /// </param>
        /// <returns>
        /// the security token
        /// </returns>
        public virtual SecurityToken IssueToken(IWSTrustChannelContract channel, string serviceAddress, SecurityToken actAsToken = null, SecurityToken onBehalfOf = null)
        {
            var rst = new RequestSecurityToken(RequestTypes.Issue)
            {
                AppliesTo = new EndpointAddress(serviceAddress)
            };

            if (actAsToken != null)
            {
                rst.ActAs = new SecurityTokenElement(actAsToken);
            }

            if (onBehalfOf != null)
            {
                rst.OnBehalfOf = new SecurityTokenElement(onBehalfOf);
            }

            RequestSecurityTokenResponse rstr;

            return(channel.Issue(rst, out rstr));
        }
Esempio n. 12
0
        /// <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);
        }
Esempio n. 13
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);
        }
Esempio n. 14
0
        public bool Logoff(string userName, string password, SecurityToken sessionToken, string securityServerURL)
        {
            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;

                RequestSecurityToken rst = new RequestSecurityToken(RequestTypes.Cancel)
                {
                    CancelTarget = new SecurityTokenElement(sessionToken)
                };

                IWSTrustChannelContract channel = factory.CreateChannel();

                RequestSecurityTokenResponse response = channel.Cancel(rst);

                return(response.RequestedTokenCancelled);
            }
        }
Esempio n. 15
0
 private SecurityToken GetSecurityToken(IWSTrustChannelContract channel, RequestSecurityToken rst)
 {
     try
     {
         RequestSecurityTokenResponse rstr = null;
         var token = channel.Issue(rst, out rstr);
         return token;
     }
     catch (Exception ex)
     {
         Logging.Exception(ex);
         Logging.DebugMessage(string.Format("Request: user={0}, stsAddress={1} thumbprint={2}", UserName, ServiceSettings.StsAddress, ThumbprintResolver.ResolveThumbprint(ServiceSettings.Thumbprint, ServiceSettings.IssuerAddress)));
         throw;
     }
 }
Esempio n. 16
0
        /// <summary>
        /// Login to the application.
        ///
        /// The login process takes two steps -
        /// First; establish the identity of the user using standard credentials.
        /// Second; use this identity to login to SIMS for the purpose of carrying out data querying.
        /// </summary>
        internal SecurityToken Login(string userName, string password, string schoolId, string tenantId)
        {
            // Temporaryily store the Identity Token issued by the identity server so that we can use it to prove our identity to the application login server.
            // Note that; although iSIMS provides both Identity and Application logins on the same service endpoint (iSIMSSTS) the Identity Service might have
            // a different endpoint where iSIMS has been integrated with an external identity management system such as ADFS, Shibboleth etc
            // ReSharper disable once RedundantAssignment
            SecurityToken identityToken = null;

            // Step 1 : Pass credentials to the identity server to get a token bearing our verified identity.
            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.
                RequestSecurityToken rst = new RequestSecurityToken(
                    // We want the security server to Issue us with a token
                    RequestTypes.Issue,
                    // We want the token type to be a Bearer token (i.e. not symmetric key or other mutually guaranteed certificate based mechanism)
                    KeyTypes.Bearer);

                // We want a token that will permit us to communicate with the application server
                rst.AppliesTo = new EndpointReference(_applicationServerAddress);

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

                // Request an identity token
                RequestSecurityTokenResponse response;
                identityToken = channel.Issue(rst, out response);
            }

            // Step 2 : Use the identity token to get a further token which can be used to access resources within the system. This token is obtained from the same
            // location in this example, but the Application Identity Server (here) and the Identity Verification Server (above) might be different URLs in Single Sign-on
            // implementations.
            using (WSTrustChannelFactory factory = GetTrustChannelFactory())
            {
                // Provide the credentials again.
                if (factory.Credentials == null)
                {
                    throw new Exception("Credentails are null");
                }
                factory.Credentials.UserName.UserName  = userName;
                factory.Credentials.UserName.Password  = password;
                factory.Credentials.SupportInteractive = false;

                // Because our communication now will be secured using our Identity Token we need to use some WIF extension methods to make sure the identity token
                // is sent as a Cookie on the SOAP call that WCF will be generating.
                factory.Credentials.UseIdentityConfiguration = true;
                factory.CreateChannelWithIssuedToken(identityToken);

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

                // create token request
                RequestSecurityToken rst = new RequestSecurityToken(
                    // We want the security server to Issue us with a token
                    RequestTypes.Issue,
                    // We want the token type to be a Bearer token (i.e. not symmetric key or other mutually guaranteed certificate based mechanism)
                    KeyTypes.Bearer);

                // Add the school ID that we claim to have access to.
                rst.AdditionalContext = new AdditionalContext();
                rst.AdditionalContext.Items.Add(new ContextItem(new Uri(SimsLoginContextSchoolClaimUrl), schoolId));
                rst.AdditionalContext.Items.Add(new ContextItem(new Uri(SimsLoginContextTenantClaimUrl), tenantId));
                // This is the endpoint for which the token will be valid.
                rst.AppliesTo = new EndpointReference(_applicationServerAddress);

                // Becuase we have already established our identity, we want this call to "Act As" us. This enables the receving web service to be passed our
                // identity in the thread principal.
                rst.ActAs = new SecurityTokenElement(identityToken);

                // Request an application session token.
                RequestSecurityTokenResponse response;
                return(channel.Issue(rst, out response));
            }
        }