public override void SecureMessage(SoapEnvelope envelope, WSE.Security security) { // get server password from database string password = parentAssertion.Password; if (password == null) return; // hash password password = SHA1(password); // create username token UsernameToken userToken = new UsernameToken(parentAssertion.ServerId.ToString(), password, PasswordOption.SendNone); if (parentAssertion.signRequest || parentAssertion.encryptRequest) { // Add the token to the SOAP header. security.Tokens.Add(userToken); } if (parentAssertion.signRequest) { // Sign the SOAP message by using the UsernameToken. MessageSignature sig = new MessageSignature(userToken); security.Elements.Add(sig); } if (parentAssertion.encryptRequest) { // we don't return any custom SOAP headers // so, just encrypt a message Body EncryptedData data = new EncryptedData(userToken); // encrypt custom headers for (int index = 0; index < envelope.Header.ChildNodes.Count; index++) { XmlElement child = envelope.Header.ChildNodes[index] as XmlElement; // find all SecureSoapHeader headers marked with a special attribute if (child != null && child.NamespaceURI == "http://smbsaas/websitepanel/server/") { // create ID attribute for referencing purposes string id = Guid.NewGuid().ToString(); child.SetAttribute("Id", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", id); // Create an encryption reference for the custom SOAP header. data.AddReference(new EncryptionReference("#" + id)); } } security.Elements.Add(data); } }
public override void SecureMessage(SoapEnvelope envelope, WSE.Security security) { // create username token UsernameToken userToken = new UsernameToken(parentAssertion.Username, parentAssertion.Password, PasswordOption.SendNone); // Add the token to the SOAP header. security.Tokens.Add(userToken); // Sign the SOAP message by using the UsernameToken. MessageSignature sig = new MessageSignature(userToken); security.Elements.Add(sig); // Encrypt SOAP message EncryptedData data = new EncryptedData(userToken); security.Elements.Add(data); }
private void CallWebService(int a, int b, string url) { // Instantiate an instance of the web service proxy AddNumbers serviceProxy = new AddNumbers(); SoapContext requestContext = serviceProxy.RequestSoapContext; // Get our security token UsernameToken token = token = new UsernameToken(user, pass, PasswordOption.SendHashed); // Add the signature element to a security section on the request // to sign the request requestContext.Security.Tokens.Add(token); requestContext.Security.Elements.Add(new MessageSignature(token)); // requestContext.Timestamp.Ttl = 6000000; // Call the service if (url != null) serviceProxy.Url = url; Console.WriteLine("Calling {0}", serviceProxy.Url); int sum = serviceProxy.AddInt(a, b); // Success! string message = string.Format("{0} + {1} = {2}", a, b, sum); Console.WriteLine("Web Service returned: {0}", message); }
private void btnVerifyApplication_Click(object sender, System.EventArgs e) { StreamReader reader = new StreamReader(this.txtSignedApplication.Text); string hashedPassword = HashPassword(txtUsername.Text, txtPassword.Text); UsernameToken token = new UsernameToken(txtUsername.Text, hashedPassword, PasswordOption.SendPlainText); token.Id = "LicenseToken"; client.Security = new Security(); client.Security.Tokens.Add(token); bool result = client.VerifyApplicationSignature(reader.BaseStream); reader.Close(); if ( result ) { XmlDocument enc = new XmlDocument(); enc.Load(this.txtSignedApplication.Text); XmlDocument newDoc = Decrypt(enc); MessageBox.Show(newDoc.DocumentElement.InnerXml); MessageBox.Show("This is a scripting application.", "GB", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("This is an invalid scripting application.", "GB", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public static void ApplyAutheticationTicket(WebServicesClientProtocol protocol, string userName, string password) { UsernameToken token = GetUsernameToken(userName, password, PasswordOption.SendPlainText); protocol.SetClientCredential(token); protocol.SetPolicy(new TpPolicy()); }
private static void SoapClientProxy() { //init web service proxy PatientServiceProxy serviceProxy = new PatientServiceProxy(); //init UsernameToken, password is the reverted string of username, the same logic in AuthenticateToken // of ServiceUsernameTokenManager class. UsernameToken token = new UsernameToken("pas-appt-ws-user", "pas-appt-ws-user-pwd", PasswordOption.SendPlainText); // Set the token onto the proxy serviceProxy.SetClientCredential(token); // Set the ClientPolicy onto the proxy serviceProxy.SetPolicy("ClientPolicy"); //invoke the HelloMyFriend web service method try { var res = serviceProxy.searchHKPMIPatientByCaseNo(new WebProxy.searchHKPMIPatientByCaseNo { caseNo = "HN03191100Y", hospitalCode = "HV" }); var resStr = XmlHelper.XmlSerializeToString(res); Console.WriteLine(resStr); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
/// <summary> /// Returns the password or password equivalent for the username provided. /// </summary> /// <param name="token">The username token</param> /// <returns>The password (or password equivalent) for the username</returns> protected override string AuthenticateToken(UsernameToken token) { string password = ServerConfiguration.Security.Password; if (String.IsNullOrEmpty(password)) throw new Exception("Empty password"); return password; }
public CustomSecurityClientOutputFilter(CustomSecurityAssertion parentAssertion) : base(parentAssertion.ServiceActor, true) { userToken = new UsernameToken(parentAssertion.Username.Trim(), parentAssertion.Password.Trim(), PasswordOption.SendPlainText); signatureToken = GetSecurityToken(); sig = new MessageSignature(signatureToken); }
/// <summary> /// Returns the password or password equivalent for the username provided. /// Adds a principal to the token with user's roles. /// </summary> /// <param name="token">The username token</param> /// <returns>The password (or password equivalent) for the username</returns> protected override string AuthenticateToken(UsernameToken token) { Customer ThisCustomer = new Customer(token.Username, true); bool LoginOk = true; if (ThisCustomer.CustomerID <= 0) { LoginOk = false; } if (LoginOk && (ThisCustomer.BadLoginCount >= AppLogic.AppConfigNativeInt("MaxBadLogins") && ThisCustomer.LockedUntil > DateTime.Now)) { LoginOk = false; } if (LoginOk && (!ThisCustomer.Active)) { LoginOk = false; } if (LoginOk && (ThisCustomer.PwdChanged.AddDays(AppLogic.AppConfigUSDouble("AdminPwdChangeDays")) < DateTime.Now || ThisCustomer.PwdChangeRequired)) { LoginOk = false; } if (LoginOk) { HttpContext.Current.Items.Add("WSIAuthenticateTokenReceived", "true"); HttpContext.Current.User = new AspDotNetStorefrontPrincipal(ThisCustomer); return(ThisCustomer.Password); } return(null); }
private static void addSecurityHeader(Microsoft.Web.Services3.WebServicesClientProtocol service) { UsernameToken userToken = new UsernameToken(AuthenticationUtils.UserName, AuthenticationUtils.Ticket, (PasswordOption)2); service.RequestSoapContext.Security.Timestamp.TtlInSeconds = (long)300; service.RequestSoapContext.Security.Tokens.Add(userToken); }
private void CallWebService(int a, int b, string url) { // Instantiate an instance of the web service proxy AddNumbers serviceProxy = new AddNumbers(); SoapContext requestContext = serviceProxy.RequestSoapContext; // Get our security token UsernameToken token = token = new UsernameToken(user, pass, PasswordOption.SendHashed); // Add the signature element to a security section on the request // to sign the request requestContext.Security.Tokens.Add(token); requestContext.Security.Elements.Add(new MessageSignature(token)); // requestContext.Timestamp.Ttl = 6000000; // Call the service if (url != null) { serviceProxy.Url = url; } Console.WriteLine("Calling {0}", serviceProxy.Url); int sum = serviceProxy.AddInt(a, b); // Success! string message = string.Format("{0} + {1} = {2}", a, b, sum); Console.WriteLine("Web Service returned: {0}", message); }
protected override string AuthenticateToken(UsernameToken token) { LoginUserStatus loginUserStatus; try { SiteManager siteManager = Users.GetUser(0, token.Identity.Name, false, false) as SiteManager; if (siteManager != null && siteManager.IsAdministrator) { HiContext arg_29_0 = HiContext.Current; siteManager.Password = HiCryptographer.Decrypt(token.Password); loginUserStatus = Users.ValidateUser(siteManager); } else { loginUserStatus = LoginUserStatus.InvalidCredentials; } } catch { loginUserStatus = LoginUserStatus.InvalidCredentials; } if (loginUserStatus == LoginUserStatus.Success) { return(token.Password); } return(HiCryptographer.CreateHash(token.Password)); }
private CEUtil(string ceUri, string osName, string ceUser, string password, LogMsg logMsg) { #if (P8_451) // P8 4.5 authentication UsernameToken token = new UsernameToken(ceUser, password, PasswordOption.SendPlainText); UserContext.SetProcessSecurityToken(token); #else // P8 5.0 authentication UsernameCredentials cred = new UsernameCredentials(ceUser, password); ClientContext.SetProcessCredentials(cred); #endif conn = Factory.Connection.GetConnection(ceUri); isCredentialsEstablished = true; // Get domain name PropertyFilter pf = new PropertyFilter(); pf.AddIncludeProperty(0, null, null, "Name", null); pf.AddIncludeProperty(0, null, null, "Id", null); domain = Factory.Domain.FetchInstance(conn, null, null); objStore = Factory.ObjectStore.FetchInstance(domain, osName, null); // Successfully initialized CEUtil object: save singleton instance this.logMsg = logMsg; gCEUtil = this; }
protected override string AuthenticateToken(UsernameToken token) { string[] WebServiceUsers = ConfigurationManager.AppSettings["WebServiceUsers"].Split(",".ToCharArray()); string[] WebServicePasswords = ConfigurationManager.AppSettings["WebServicePasswords"].Split(",".ToCharArray()); switch (token.PasswordOption) { case PasswordOption.SendPlainText: { int useridx = Array.IndexOf(WebServiceUsers, token.Username); if (useridx >= 0) return WebServicePasswords[useridx]; break; } case PasswordOption.SendHashed: { int useridx = Array.IndexOf(WebServiceUsers, token.Username); if (useridx >= 0) return CryptographyHelper.CalculateHash(WebServicePasswords[useridx], CryptographyHelper.HashMode.SHA1); break; } } return ""; }
public object BeforeSendRequest(ref Message request, System.ServiceModel.IClientChannel channel) { UsernameToken token = new UsernameToken(Username, Password, PasswordOption.SendPlainText); XmlElement securityToken = token.GetXml(new XmlDocument()); // Modificamos el XML Generado. // var nodo = securityToken.GetElementsByTagName("wsse:Nonce").Item(0); //nodo?.RemoveAll(); MessageHeader securityHeader = MessageHeader.CreateHeader("Security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", securityToken, false); request.Headers.Add(securityHeader); MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue); request = buffer.CreateMessage(); try { System.IO.File.WriteAllText(@"c:\temp\" + DateTime.Now.ToString("MMddyyyyhhmmssfff") + ".xml", request.ToString()); } catch { } return(Convert.DBNull); }
/// <summary> /// load files from FieldManagmentService /// </summary> /// <param name="service"></param> private static void CallFieldManagementService(ServiceConfig service) { var crmOnDemandFieldManagementService = new CrmOnDemandFieldManagementService.FieldManagementService(); var requestContext = crmOnDemandFieldManagementService.RequestSoapContext; UsernameToken userToken = new UsernameToken(service.Username, service.Password, PasswordOption.SendPlainText); requestContext.Security.Tokens.Add(userToken); var fieldManagementReadAll_Input = new CrmOnDemandFieldManagementService.FieldManagementReadAll_Input(); fieldManagementReadAll_Input.IncludeAll = true; log.Info("Making service call to " + FIELD_MANAGEMENT_READ_ALL); var fieldManagementReadAll_Output = crmOnDemandFieldManagementService.FieldManagementReadAll(fieldManagementReadAll_Input); log.Debug("Service call to " + FIELD_MANAGEMENT_READ_ALL + " returned successfully"); XmlTextWriter writer = new XmlTextWriter(service.ResponseFileName, null); writer.Formatting = Formatting.Indented; crmOnDemandFieldManagementService.ResponseSoapContext.Envelope.WriteContentTo(writer); writer.Flush(); var msg = FIELD_MANAGEMENT_READ_ALL + " output saved to file: " + service.ResponseFileName; log.Info(msg); Console.WriteLine(msg); }
protected override string AuthenticateToken(UsernameToken token) { LoginUserStatus invalidCredentials = LoginUserStatus.InvalidCredentials; try { SiteManager user = Users.GetUser(0, token.Identity.Name, false, false) as SiteManager; if ((user != null) && user.IsAdministrator) { HiContext current = HiContext.Current; user.Password = Cryptographer.Decrypt(token.Password); invalidCredentials = Users.ValidateUser(user); } else { invalidCredentials = LoginUserStatus.InvalidCredentials; } } catch { invalidCredentials = LoginUserStatus.InvalidCredentials; } if (invalidCredentials == LoginUserStatus.Success) { return(token.Password); } return(Cryptographer.CreateHash(token.Password)); }
public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel) { // Use the WSE 3.0 security token class var option = PasswordOption.SendHashed; if (string.IsNullOrEmpty(Username) || string.IsNullOrEmpty(Password)) { option = PasswordOption.SendPlainText; } UsernameToken token = new UsernameToken(this.Username, this.Password, option); // Serialize the token to XML XmlDocument xmlDoc = new XmlDocument(); XmlElement securityToken = token.GetXml(xmlDoc); // find nonce and add EncodingType attribute for BSP compliance XmlNamespaceManager nsMgr = new XmlNamespaceManager(xmlDoc.NameTable); nsMgr.AddNamespace("wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"); XmlNodeList nonces = securityToken.SelectNodes("//wsse:Nonce", nsMgr); XmlAttribute encodingAttr = xmlDoc.CreateAttribute("EncodingType"); encodingAttr.Value = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary"; if (nonces.Count > 0) { nonces[0].Attributes.Append(encodingAttr); //nonces[0].Attributes[0].Value = "foo"; } // MessageHeader securityHeader = MessageHeader.CreateHeader("Security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", securityToken, false); request.Headers.Add(securityHeader); // complete return(Convert.DBNull); }
public void TestMethod1() { ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; QueryPESEL queryPesel = new QueryPESEL(); X509Certificate x509Certificate = new X509Certificate(@"F:\path\cert.pfx", "pass"); UsernameToken userToken = new UsernameToken("username", "pass", PasswordOption.SendPlainText); queryPesel.RequestSoapContext.IdentityToken = userToken; queryPesel.ClientCertificates.Add(x509Certificate); queryPesel.SetClientCredential(userToken); // queryPesel.RequestSoapContext.Security.Tokens.Add(userToken); PeselVerificationResponse result = queryPesel.submitQuestion(new PeselVerificationRequest { businessUserId = 0, pesel = "12345678905" }); Assert.IsNotNull(result); }
public void SetRegistrarSecurity() { UsernameToken userToken = new UsernameToken("*****@*****.**", "kennwort", PasswordOption.SendPlainText); SoapContext requestContext = RequestSoapContext; requestContext.Security.Tokens.Clear(); requestContext.Security.Tokens.Add(userToken); }
public void SetTechnicalSupportUserSecurity() { UsernameToken userToken = new UsernameToken("[email protected]%1987654323", "kennwort", PasswordOption.SendPlainText); SoapContext requestContext = RequestSoapContext; requestContext.Security.Tokens.Clear(); requestContext.Security.Tokens.Add(userToken); }
protected override string AuthenticateToken(UsernameToken token) { // Authenticate here. // If succeess, return an authenticated IPrincipal and the user's password as shown. // If failure, throw an exception of your choosing. token.Principal = principal; return(password); }
public void SetDefaultSecurity() { // Setup WS-Security authentication UsernameToken userToken = new UsernameToken(Username, Password, PasswordOption.SendPlainText); SoapContext requestContext = RequestSoapContext; requestContext.Security.Tokens.Add(userToken); //requestContext.Security.Timestamp.TtlInSeconds = SvcConfig.TtlInSeconds; }
public TransmitResult TransmitFile(string localFile, string remoteServer, string userid, string password) { var file = new FileInfo(localFile); if (!file.Exists) { return(new TransmitResult { Message = string.Format("Invalid filepath: \"{0}\".", localFile), Transmitted = false, }); } var token = new UsernameToken(ClientIdentifier, ClientIdentifier, PasswordOption.SendNone); var gisbProxy = new GisbProxyService { Url = remoteServer }; gisbProxy.RequestSoapContext.Security.Tokens.Add(token); gisbProxy.RequestSoapContext.Security.Elements.Add(new MessageSignature(token)); gisbProxy.RequestSoapContext.Security.Timestamp.TtlInSeconds = 60; gisbProxy.RequestSoapContext.Security.Elements.Add(new EncryptedData(token)); gisbProxy.Credentials = new CredentialCache { { new Uri(remoteServer), "Basic", new NetworkCredential(userid, password) } }; try { using (var stream = file.OpenRead()) using (var reader = new StreamReader(stream)) { var content = reader.ReadToEnd(); var bytes = Encoding.UTF8.GetBytes(content); var hash = (new MD5CryptoServiceProvider()).ComputeHash(bytes); using (gisbProxy) { var resp = gisbProxy.SendEDI(bytes, hash, file.Name.Substring(0, 3)); return(new TransmitResult { Message = resp.ErrorMessage, Transmitted = resp.SuccessFlag, }); } } } catch (Exception ex) { return(new TransmitResult { Message = ex.Message, Transmitted = false, }); } }
public static UsernameToken GetUsernameToken(string username, string password, PasswordOption passwordOption) { var token = new UsernameToken(username, password, passwordOption); var securityTokenManager = SecurityTokenManager.GetSecurityTokenManagerByTokenType(WSTrust.TokenTypes.UsernameToken); securityTokenManager.CacheSecurityToken(token); return token; }
static void Main(string[] args) { Console.Write("Login: "******"Password: "******"Try to connect using login:{0} password:{1}", login, pass)); var authenticationService = new AuthenticationService(); var token = new UsernameToken("test_user", "12345678", PasswordOption.SendPlainText); authenticationService.RequestSoapContext.Security.Tokens.Add(token); var credentials = new Credentials(); credentials.Login = login; credentials.Password = pass; credentials.LanId = new decimal(1); credentials.AppCode = "I"; var sessionHash = authenticationService.authenticate(credentials); Console.WriteLine("Sessioh hash: {0}", sessionHash); var personService = new PersonService(); var user = personService.getCurrentUser(sessionHash); var projects = personService.getUserProjectsList(sessionHash, (decimal)user.Id); decimal projectId = 0; foreach (var project in projects) { Console.WriteLine("Project id: {0}, project name: {1}", project.Key, project.Value); if (project.Value.Equals("ABC-TST")) { projectId = (decimal)project.Key; personService.changeProject(sessionHash, projectId); } } if (projectId != 0) { var requirementService = new RequirementService(); var requirement = new Requirement { ItemName = "Test req", ParentItemId = projectId }; requirement = requirementService.addRequirement(sessionHash, requirement); if (requirement.Id != 0) { Console.WriteLine("Requirement was added with id: {0}", requirement.Id); } } else { Console.WriteLine("Project wasn't changed"); } Console.ReadLine(); authenticationService.invalidateSession(sessionHash); }
public override void SecureMessage(SoapEnvelope envelope, WSE.Security security) { // get server password from database string password = parentAssertion.Password; if (password == null) { return; } // hash password password = CryptoUtils.SHA1(password); // create username token UsernameToken userToken = new UsernameToken(parentAssertion.ServerId.ToString(), password, PasswordOption.SendNone); if (parentAssertion.signRequest || parentAssertion.encryptRequest) { // Add the token to the SOAP header. security.Tokens.Add(userToken); } if (parentAssertion.signRequest) { // Sign the SOAP message by using the UsernameToken. MessageSignature sig = new MessageSignature(userToken); security.Elements.Add(sig); } if (parentAssertion.encryptRequest) { // we don't return any custom SOAP headers // so, just encrypt a message Body EncryptedData data = new EncryptedData(userToken); // encrypt custom headers for (int index = 0; index < envelope.Header.ChildNodes.Count; index++) { XmlElement child = envelope.Header.ChildNodes[index] as XmlElement; // find all SecureSoapHeader headers marked with a special attribute if (child != null && child.NamespaceURI == "http://com/SolidCP/server/") { // create ID attribute for referencing purposes string id = Guid.NewGuid().ToString(); child.SetAttribute("Id", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", id); // Create an encryption reference for the custom SOAP header. data.AddReference(new EncryptionReference("#" + id)); } } security.Elements.Add(data); } }
public CustomSecurityClientOutputFilter(CustomSecurityAssertion parentAssertion) : base(parentAssertion.ServiceActor, true) { String username = parentAssertion.username; String password = parentAssertion.password; userToken = new UsernameToken(username.Trim(), password.Trim(), PasswordOption.SendPlainText); signatureToken = GetSecurityToken("CN=TestSSSCert"); sig = new MessageSignature(signatureToken); }
public override void SecureMessage(SoapEnvelope envelope, Security security) { UsernameToken userToken = new UsernameToken( parentAssertion.username, parentAssertion.password, PasswordOption.SendHashed); // Add the token to the SOAP header. security.Tokens.Add(userToken); }
/// <summary> /// Returns the password or password equivalent for the username provided. /// </summary> /// <param name="token">The username token</param> /// <returns>The password (or password equivalent) for the username</returns> protected override string AuthenticateToken(UsernameToken token) { string password = ServerConfiguration.Security.Password; if (String.IsNullOrEmpty(password)) { throw new Exception("Empty password"); } return(password); }
public static UsernameToken GetUsernameToken(string username, string password, PasswordOption passwordOption) { var token = new UsernameToken(username, password, passwordOption); var securityTokenManager = SecurityTokenManager.GetSecurityTokenManagerByTokenType(WSTrust.TokenTypes.UsernameToken); securityTokenManager.CacheSecurityToken(token); return(token); }
public LETSIRTE_Service(string sessionID, string secret) : base() { UsernameToken token = new UsernameToken(sessionID, secret, PasswordOption.SendHashed); // make credentials available to send with the request SetClientCredential(token); // indicate that credentials should be sent with the request SetPolicy("Client"); }
public object BeforeSendRequest(ref Message request, IClientChannel channel) { UsernameToken authentication = new UsernameToken(remoteServiceUsername, remoteServicePassword, PasswordOption.SendPlainText); //Plain text is server requirement, we cannot do anything var webUserHeader = MessageHeader.CreateHeader("Security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", authentication.GetXml(new XmlDocument())); request.Headers.Add(webUserHeader); return(null); }
/// <summary> /// Returns the password or password equivalent for the username provided. /// </summary> /// <param name="token">The username token</param> /// <returns>The password (or password equivalent) for the username</returns> protected override string AuthenticateToken(UsernameToken token) { // try to load user account UserInfoInternal user = UserController.GetUserInternally(token.Username); if (user == null) return null; SecurityContext.SetThreadPrincipal(user); return user.Password; }
protected void Page_Load(object sender, EventArgs e) { MyService.ServiceWse wse = new MyService.ServiceWse(); wse.SetPolicy("UserTokenClient"); UsernameToken token = new UsernameToken("naynish", "bhairav@12", PasswordOption.SendPlainText); wse.SetClientCredential(token); SoapContext reqContext = wse.RequestSoapContext; reqContext.Security.Timestamp.TtlInSeconds = 120; reqContext.Security.Tokens.Add(token); Label1.Text = wse.HelloWorld(); }
FFIECPublicWebService.RetrievalService GetRetrievalServiceProxy(FilingProcessCommandArgs commandLineArgs) { FFIECPublicWebService.RetrievalService proxy = new FFIECPublicWebService.RetrievalService(); UsernameToken userToken = new UsernameToken(commandLineArgs.Credentials.UserName, commandLineArgs.Credentials.Password, PasswordOption.SendHashed); proxy.RequestSoapContext.Security.Tokens.Add(userToken); return(proxy); }
public object BeforeSendRequest(ref Message request, System.ServiceModel.IClientChannel channel) { UsernameToken token = new UsernameToken(this.Username, this.Password, PasswordOption.SendHashed); XmlElement securityToken = token.GetXml(new XmlDocument()); MessageHeader securityHeader = MessageHeader.CreateHeader("Security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", securityToken, false); request.Headers.Add(securityHeader); return(Convert.DBNull); }
public override void SecureMessage(SoapEnvelope envelope, Security security) { UsernameToken userToken = new UsernameToken( parentAssertion.username, parentAssertion.password, PasswordOption.SendHashed); // we don't send password over network // but we just use username/password to sign/encrypt message // Add the token to the SOAP header. security.Tokens.Add(userToken); }
protected void SetUsernameToken(UsernameToken userToken) { if (webService.RequestSoapContext.Security.Tokens.Contains(userToken)) { return; } webService.RequestSoapContext.Security.Tokens.Add(userToken); var sig = new MessageSignature(userToken); webService.RequestSoapContext.Security.Elements.Add(sig); webService.RequestSoapContext.Security.Timestamp.TtlInSeconds = 60; }
/// <summary> /// Adds the user token. /// </summary> /// <param name="username"> The username.</param> /// <param name="password"> The user password.</param> public static void AddUserToken(string username, string password) { Username = username; string hashedPassword = HashPassword(username, password); UsernameToken token = new UsernameToken(username, hashedPassword, PasswordOption.SendPlainText); token.Id = "LicenseToken"; if ( client.Security != null ) { client.Security = new Security(); } client.Security.Tokens.Add(token); }
/// <summary> /// Returns the password or password equivalent for the username provided. /// </summary> /// <param name="token">The username token</param> /// <returns>The password (or password equivalent) for the username</returns> protected override string AuthenticateToken(UsernameToken token) { // try to load user account UserInfoInternal user = UserController.GetUserInternally(token.Username); if (user == null) { return(null); } SecurityContext.SetThreadPrincipal(user); return(user.Password); }
/// <summary> /// Returns the password or password equivalent for the username provided. /// </summary> /// <param name="token">The username token</param> /// <returns>The password (or password equivalent) for the username</returns> protected override string AuthenticateToken(UsernameToken token) { string username = token.Username; // it's up to you where you will get a password for some user // you may: // 1) get the password hash from web.config or system registry // if you are implementing per-server security // 2) get the password from the database or XML file for the given user name // for example purposes we just return a reversed value of username char[] ch = username.ToCharArray(); Array.Reverse(ch); return new String(ch); }
public CustomSecurityClientOutputFilter(CustomSecurityAssertion parentAssertion) : base(parentAssertion.ServiceActor, true) { String username = parentAssertion.username; String password = parentAssertion.password; XmlElement binaryToken = parentAssertion.binaryToken; if (binaryToken == null) { userToken = new UsernameToken(username.Trim(), password.Trim(), PasswordOption.SendPlainText); } else { issuedToken = new IssuedToken(binaryToken); } }
private static void serviceClientSetting(WebServicesClientProtocol serviceClient, string url, string username = null, string password = null, int timeout = -1) { serviceClient.Url = url; /* timeout is 0 if config verb EBSServiceTimeout is not defined. * It is set at the _sr_client CS_SERVICEREQUEST_PUB_Service() instance * level, so all the ws calls (from this proxy client) have this timeout setting */ serviceClient.Timeout = timeout == 0 ? -1 : timeout; if (!String.IsNullOrWhiteSpace(username) && !String.IsNullOrWhiteSpace(password)) { // add wsse:Security headers. UsernameToken userNameToken = new UsernameToken(username, password, PasswordOption.SendPlainText); SoapContext soapContext = serviceClient.RequestSoapContext; soapContext.Security.Tokens.Add(userNameToken); } }
public CustomSecurityClientOutputFilter(CustomSecurityAssertion parentAssertion) : base(parentAssertion.ServiceActor, true) { if (parentAssertion.BinaryToken == null) { userToken = new UsernameToken(parentAssertion.Username.Trim(), parentAssertion.Password.Trim(), PasswordOption.SendPlainText); signatureToken = GetSecurityToken(); parentAssertion.SecurityToken = signatureToken; } else { issuedToken = new IssuedToken(parentAssertion.BinaryToken); signatureToken = parentAssertion.SecurityToken; samlAssertionId = parentAssertion.BinaryToken.Attributes.GetNamedItem("ID").Value; } sig = new MessageSignature(signatureToken); }
internal static Token GenerateTokenWssUser(string Username, string Password) { //********************************** TOKEN ***************************************************** UsernameToken token = new UsernameToken(Username, Password, PasswordOption.SendPlainText); XmlElement securityToken = token.GetXml(new XmlDocument()); Token _token = new Token(); _token.user = securityToken["wsse:Username"].InnerText; _token.pass = securityToken["wsse:Password"].InnerText; _token.encoding = securityToken["wsse:Nonce"].InnerText; _token.created = securityToken["wsu:Created"].InnerText; //********************************************************************************************* return _token; }
// This method returns the password for the provided username // WSE will determine if they match protected override string AuthenticateToken(UsernameToken token) { string username = token.Username; // In real site, would query database or check XML file... if (username == "dan") { return "secret"; } else if (username == "jenny") { return "opensesame"; } else { return ""; } }
protected override string AuthenticateToken(UsernameToken token) { LoginUserStatus invalidCredentials = LoginUserStatus.InvalidCredentials; try { SiteManager user = Users.GetUser(0, token.Identity.Name, false, false) as SiteManager; if ((user != null) && user.IsAdministrator) { HiContext current = HiContext.Current; user.Password = Cryptographer.Decrypt(token.Password); invalidCredentials = Users.ValidateUser(user); } else { invalidCredentials = LoginUserStatus.InvalidCredentials; } } catch { invalidCredentials = LoginUserStatus.InvalidCredentials; } if (invalidCredentials == LoginUserStatus.Success) { return token.Password; } return Cryptographer.CreateHash(token.Password); }
/// <summary> /// Authenticates the token. /// </summary> /// <param name="token"> The UsernameToken to authenticate.</param> /// <returns> Returns the user's password.</returns> protected override string AuthenticateToken(UsernameToken token) { string result = string.Empty; if ( token.Id == "LicenseToken" ) { // Login user if ( ValidateUsernameToken(token) ) { result = token.Password; } else { throw new SoapException( "Missing security token", SoapException.ClientFaultCode); } } return result; }
private bool ValidateUsernameToken(UsernameToken token) { DatabaseConfigurationHandler databaseConfigManager = new DatabaseConfigurationHandler(); DatabaseConfiguration databaseConfiguration = (DatabaseConfiguration)databaseConfigManager.Load("serviceDatabaseConfiguration",string.Empty); UserDatabaseManager userDatabase = new UserDatabaseManager(); string password = userDatabase.GetPasswordToken(databaseConfiguration.ConnectionString,token.Username); if ( password.Length == 0 ) { return false; } else { if ( HashPassword(token.Username, password) == token.Password ) { return true; } else { return false; } } }
/// <summary> /// Request the get National ID data from the live webservice. /// </summary> /// <param name="validNID">refrence for National ID number</param> /// <returns></returns> public static NationalIdData? RequestNationalIDData(string validNID) { if (validNID == "11111111111111" || validNID == "28409012601094") { NationalIdData nidStruct1 = new NationalIdData(); nidStruct1.FirstName = "Steven"; nidStruct1.FatherName = "-----"; nidStruct1.FamilyName = "Yousef"; nidStruct1.SureName = "Sawires"; return nidStruct1; } try { G2GHeader header = new G2GHeader(); header.Agency = "Agency"; header.Application = "Application"; header.Citizen = "Citizen"; header.Employee = "Employee"; header.Entity = "Entity"; header.Office = "Office"; PersonProfileId personProfileId = new PersonProfileId(); personProfileId.idNum = validNID; personProfileId.organizationID = "MOHP"; personProfileId.orgIpAddres = "163.121.135.51"; personProfileId.prkey = "mohp"; personProfileId.stype = "s"; PersonalProfileServiceImpl objService = new PersonalProfileServiceImpl(); string UserTokenWCF = System.Configuration.ConfigurationManager.AppSettings["UserTokenWCF"].ToString(); string PassTokenWCF = System.Configuration.ConfigurationManager.AppSettings["PassTokenWCF"].ToString(); UsernameToken token = new UsernameToken(UserTokenWCF, PassTokenWCF, PasswordOption.SendPlainText); objService.SetClientCredential(token); objService.SetPolicy("ClientPolicy"); objService.G2GHeaderValue = header; PersonProfile Aperson = objService.getPersonProfileById(personProfileId); NationalIdData nidStruct = new NationalIdData(); nidStruct.FirstName = Aperson.firstName; string[] names = Aperson.lastNames.Split(' '); if (names.Length < 2) nidStruct.FatherName = names[0]; else if (names.Length < 3) { nidStruct.FatherName = names[0]; nidStruct.FamilyName = names[1]; } else if (names.Length >= 3) { nidStruct.FatherName = names[0]; nidStruct.FamilyName = names[1]; nidStruct.SureName = names[2]; } //System.Net.ServicePointManager.CertificatePolicy = new TrsutAll(); //CsoCheckPrsService.Export1_CsoCheckPrsHttpService objService = new CsoCheckPrsService.Export1_CsoCheckPrsHttpService(); //CsoCheckPrsService.CSOOutput objOutput = new CsoCheckPrsService.CSOOutput(); //objOutput = objService.csogetPersonDetByIdnum(validNID, "MOHP", "163.121.135.51", "mohp", "S"); //string fname = objOutput.firstName; //string[] lastNames = objOutput.lastNames.Split(' '); //string mName = lastNames[0].ToString(); //string Lname = lastNames[1].ToString(); //string Sname = "" ; //if (lastNames.Length > 2) //Sname = lastNames[2].ToString(); //NationalIdData nidStruct = new NationalIdData(); //nidStruct.FirstName = fname; //nidStruct.FatherName = mName; //nidStruct.FamilyName = Lname; //nidStruct.SureName = Sname; return nidStruct; } catch (FaultException ex) { NationalIdData nidStruct2 = new NationalIdData(); nidStruct2.FirstName = ex.Action+ex.Code+ ex.Message + ex.Source ; return nidStruct2; //return null; } catch(Exception ex) { NationalIdData nidStruct2 = new NationalIdData(); nidStruct2.FirstName = "Message: " + ex.Message + " --- Source: " + ex.Source + " --- Data: " + ex.Data.ToString() + " --- StackTrace: " + ex.StackTrace; return nidStruct2; //return null; } }
public CustomSecurityClientOutputFilter(CustomSecurityAssertion parentAssertion) : base(parentAssertion.ServiceActor, true) { userToken = new UsernameToken(parentAssertion.username, parentAssertion.password, PasswordOption.SendPlainText); }
public MailingService CreateMailingService() { if (String.IsNullOrEmpty(this.MessageStudioApiUrl)) throw new ConfigurationErrorsException("The MessageStudio API URL is not present in the configuration file"); ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback((o, cert, chain, sslerr) => { return true; }); var svc = new MailingService(this.MessageStudioApiUrl); UsernameToken userToken = new UsernameToken(this.UserName, this.Password, PasswordOption.SendPlainText); SoapContext ctx = svc.RequestSoapContext; ctx.Security.Tokens.Add(userToken); svc.Pipeline.OutputFilters.Insert(0, new InjectOrganizationInWsseSecurity("ATTI")); svc.RequestEncoding = System.Text.Encoding.UTF8; return svc; }
/// <summary> /// Initializes a new instance of the <see cref="ClientInfo"/> class. /// </summary> /// <param name="parent">An <see cref="ClientHelper"/> object.</param> public ClientInfo(ClientHelper parent) { m_clientID = Guid.Empty; m_clientType = Common.GetApplicationType(); m_machineName = Environment.MachineName; // Get the user login id. if (!string.IsNullOrEmpty(UserInfo.RemoteUserID)) m_userName = UserInfo.RemoteUserID; else m_userName = UserInfo.CurrentUserID; // Get the type of client application. if (ClientType == ApplicationType.WindowsCui || ClientType == ApplicationType.WindowsGui) m_clientName = AppDomain.CurrentDomain.FriendlyName; else if (ClientType == ApplicationType.Web) m_clientName = HttpContext.Current.Request.ApplicationPath; // Initialize the serialized identity token. m_serializedIdentityToken = string.Empty; if (parent != null && parent.AuthenticationMethod != IdentityToken.None) { SecurityToken token = null; StringWriter stringWriter = new StringWriter(); XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter); SerializableTokenWrapper<SecurityToken> serializer = new SerializableTokenWrapper<SecurityToken>(); try { // Create a token based on the selected method. if (parent.AuthenticationMethod == IdentityToken.Ntlm) { if (!string.IsNullOrEmpty(parent.AuthenticationInput) && parent.AuthenticationInput.Contains(":")) { // Input format: <username>:<password> string[] loginParts = parent.AuthenticationInput.Split(':'); token = new UsernameToken(loginParts[0], loginParts[1], PasswordOption.SendPlainText); } } else if (parent.AuthenticationMethod == IdentityToken.Kerberos) { if (!string.IsNullOrEmpty(parent.AuthenticationInput) && parent.AuthenticationInput.Contains("/")) { // Input format: host/<machine name> token = new KerberosToken(parent.AuthenticationInput, ImpersonationLevel.Impersonation); } } // Serialize the token to XML for transportation. if (token != null) { serializer.WriteToken(xmlTextWriter, token); m_serializedIdentityToken = stringWriter.ToString(); } } catch { // Identity token creation failed due to an exception. } } }
private void btnSign_Click(object sender, System.EventArgs e) { ScriptingApplication application = new ScriptingApplication(); application.Load(this.txtApplicationPath.Text); string encryptedXml = application.Encrypt(); string hashedPassword = HashPassword(txtUsername.Text, txtPassword.Text); UsernameToken token = new UsernameToken(txtUsername.Text, hashedPassword, PasswordOption.SendPlainText); token.Id = "LicenseToken"; // create client message. RegisterApplicationMessage message = new RegisterApplicationMessage(); message.ApplicationID = application.Header.ApplicationID; message.EncryptedScriptingApplicationXml = encryptedXml; client.Security = new Security(); client.Security.Tokens.Add(token); client.BeginRegisterScriptingApplication( message, new MessageResultHandler(SignScriptingAppInvoker), null); }
private void btnValidate_Click(object sender, System.EventArgs e) { string hashedPassword = HashPassword(txtUsername.Text, txtPassword.Text); UsernameToken token = new UsernameToken(txtUsername.Text, hashedPassword, PasswordOption.SendPlainText); token.Id = "LicenseToken"; client.Security = new Security(); client.Security.Tokens.Add(token); client.BeginGetUserDetails(new MessageResultHandler(GetUserDetailsInvoker), null); }