/// <summary>Encodes the password based on the password format.</summary> /// <param name="password">The password to encode.</param> /// <param name="format">format for encode</param> /// <returns>The encoded password.</returns> public string EncodeString(string password, MembershipPasswordFormat format) { // the password in clear format isn't encoded, so we're done if (format == MembershipPasswordFormat.Clear) { return(password); } // convert the password and salt to bytes byte[] passwordBytes = Encoding.Unicode.GetBytes(password); var saltBytes = new byte[0]; // copies the salt and the password to a byte array var passWithSaltBytes = new byte[passwordBytes.Length + saltBytes.Length]; byte[] encodedPassword; Buffer.BlockCopy(saltBytes, 0, passWithSaltBytes, 0, saltBytes.Length); Buffer.BlockCopy(passwordBytes, 0, passWithSaltBytes, saltBytes.Length, passwordBytes.Length); // generates a hash or encrypts the password if (format == MembershipPasswordFormat.Hashed) { HashAlgorithm hashAlgo = HashAlgorithm.Create(Membership.HashAlgorithmType); encodedPassword = hashAlgo.ComputeHash(passWithSaltBytes); } else { encodedPassword = EncryptPassword(passWithSaltBytes); } return(Convert.ToBase64String(encodedPassword)); }
/// <summary>Decodes the password.</summary> /// <param name="password">The password to decode.</param> /// <param name="format">The password format used to encode it.</param> /// <returns>The decoded password.</returns> public string DecodeString(string password, MembershipPasswordFormat format) { // the password in clear format isn't encoded, so we're done if (format == MembershipPasswordFormat.Clear) { return(password); } // a hashed password can't be retrieved if (format == MembershipPasswordFormat.Hashed) { return(password); //throw new ProviderException("Error, a hased password can't be retrieved"); } // otherwise decrypt the password byte[] encodedPassword = Convert.FromBase64String(password); byte[] decryptedPassword = DecryptPassword(encodedPassword); if (decryptedPassword == null) { return(null); } // returns the decoded password ignoring the salt return(Encoding.Unicode.GetString(decryptedPassword)); }
private string EncodePassword(string pass, string salt, MembershipPasswordFormat format) { if (format == MembershipPasswordFormat.Clear) { return(pass); } if (format == MembershipPasswordFormat.Hashed) { if (!Enum.IsDefined(typeof(SimpleHashAlgorithm), this.EncryptionAlgorithm)) { throw new ProviderException("Encryption algorithm not valid. Possible values are " + DebugUtility.GetDebugString(typeof(SimpleHashAlgorithm)) + " when using hashed encryption."); } return(EncryptionManager.ComputeHash(pass, (SimpleHashAlgorithm)Enum.Parse(typeof(SimpleHashAlgorithm), this.EncryptionAlgorithm), Encoding.Unicode.GetBytes(salt))); } else { if (this.EncryptionAlgorithm.ToUpper() == "DPAPI") { return(EncryptionManager.EncryptDPAPI(pass)); } if (!Enum.IsDefined(typeof(RijndaelSimpleHashAlgorithm), this.EncryptionAlgorithm)) { throw new ProviderException("Membership.HashAlgorithmType not found. Possible values are " + DebugUtility.GetDebugString(typeof(RijndaelSimpleHashAlgorithm)) + " and DPAPI"); } return(EncryptionManager.AES_Simple_Encrypt(pass, this.PasswordPassphrase, salt, this.PasswordInitVector, (RijndaelSimpleHashAlgorithm)Enum.Parse(typeof(RijndaelSimpleHashAlgorithm), this.EncryptionAlgorithm), RijndaelSimpleKeySize.Medium, 3)); } }
/// <summary> /// 初始化提供程序。 /// </summary> /// <param name="name"></param> /// <param name="config"></param> public override void Initialize(string name, NameValueCollection config) { if (String.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } base.Initialize(name, config); _maxInvalidPasswordAttempts = Convert.ToInt32(GetConfigValue(config["maxInvalidPasswordAttempts"], "5")); _passwordAttemptWindow = Convert.ToInt32(GetConfigValue(config["passwordAttemptWindow"], "10")); _minRequiredNonAlphanumericCharacters = Convert.ToInt32(GetConfigValue(config["minRequiredNonAlphanumericCharacters"], "0")); _minRequiredPasswordLength = Convert.ToInt32(GetConfigValue(config["minRequiredPasswordLength"], "6")); _passwordStrengthRegularExpression = Convert.ToString(GetConfigValue(config["passwordStrengthRegularExpression"], "\\d*")); _enablePasswordReset = Convert.ToBoolean(GetConfigValue(config["enablePasswordReset"], "true")); _enablePasswordRetrieval = Convert.ToBoolean(GetConfigValue(config["enablePasswordRetrieval"], "true")); _requiresQuestionAndAnswer = Convert.ToBoolean(GetConfigValue(config["requiresQuestionAndAnswer"], "false")); _requiresUniqueEmail = Convert.ToBoolean(GetConfigValue(config["requiresUniqueEmail"], "true")); //password 支持不可rHashed _passwordFormat = (MembershipPasswordFormat) Enum.Parse(typeof(MembershipPasswordFormat), GetConfigValue(config["passwordFormat"], "Encrypted"), true); }
public override void Initialize(string name, NameValueCollection config) { this.ApplicationName = config["applicationName"] ?? HostingEnvironment.ApplicationVirtualPath; this.enablePasswordReset = bool.Parse(config["enablePasswordReset"] ?? "true"); this.enablePasswordRetrieval = bool.Parse(config["enablePasswordRetrieval"] ?? "false"); this.maxInvalidPasswordAttempts = int.Parse(config["maxInvalidPasswordAttempts"] ?? "5"); this.minRequiredNonAlphanumericCharacters = int.Parse(config["minRequiredNonAlphanumericCharacters"] ?? "1"); this.minRequiredPasswordLength = int.Parse(config["minRequiredPasswordLength"] ?? "7"); this.passwordAttemptWindow = int.Parse(config["passwordAttemptWindow"] ?? "10"); this.passwordFormat = (MembershipPasswordFormat)Enum.Parse(typeof(MembershipPasswordFormat), config["passwordFormat"] ?? "Hashed"); this.passwordStrengthRegularExpression = config["passwordStrengthRegularExpression"] ?? string.Empty; this.requiresQuestionAndAnswer = bool.Parse(config["requiresQuestionAndAnswer"] ?? "false"); this.requiresUniqueEmail = bool.Parse(config["requiresUniqueEmail"] ?? "true"); if (this.PasswordFormat == MembershipPasswordFormat.Hashed && this.EnablePasswordRetrieval) { throw new ProviderException("Configured settings are invalid: Hashed passwords cannot be retrieved. Either set the password format to different type, or set enablePasswordRetrieval to false."); } this.mongoCollection = new MongoClient(config["connectionString"] ?? "mongodb://localhost").GetServer().GetDatabase(config["database"] ?? "ASPNETDB").GetCollection(config["collection"] ?? "Users"); this.mongoCollection.EnsureIndex("ApplicationName"); this.mongoCollection.EnsureIndex("ApplicationName", "LoweredEmail"); this.mongoCollection.EnsureIndex("ApplicationName", "LoweredUsername"); base.Initialize(name, config); }
private void Test_ChangePassword(MembershipPasswordFormat membershipPasswordFormat) { IMembershipSettings membershipSettings = Workmate.Components.InstanceContainer.MembershipSettings; membershipSettings.PasswordFormat = membershipPasswordFormat; IApplicationSettings applicationSettings = Workmate.Components.InstanceContainer.ApplicationSettings; WorkmateRoleProvider roleProvider = new WorkmateRoleProvider(); WorkmateMembershipProvider membershipProvider = new WorkmateMembershipProvider(); string password = "******"; string newPassword = "******"; IUserBasic userBasic = CreateUser(applicationSettings, this.Application, this.DummyDataManager, roleProvider, membershipProvider, password, AccountStatus.Valid); IUserBasic validatedUserBasic; ValidateUserStatus validateUserStatus = membershipProvider.ValidateUser(this.Application.ApplicationId, userBasic.Email, password, out validatedUserBasic); Assert.AreEqual(ValidateUserStatus.Valid, validateUserStatus); ChangePasswordStatus changePasswordStatus = membershipProvider.ChangePassword(this.Application.ApplicationId, userBasic, password, newPassword); Assert.AreEqual(ChangePasswordStatus.Success, changePasswordStatus); validateUserStatus = membershipProvider.ValidateUser(this.Application.ApplicationId, userBasic.Email, newPassword, out validatedUserBasic); Assert.AreEqual(ValidateUserStatus.Valid, validateUserStatus); }
public override void Initialize(string name, NameValueCollection config) { if (config == null) { throw new ArgumentNullException(nameof(config)); } if (name == null || name.Length == 0) { name = "CustomMembershipProvider"; } if (String.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", "Custom Membership Provider"); } base.Initialize(name, config); this.applicationName = GetConfigValue(config["applicationName"], System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath); this.maxInvalidPasswordAttempts = Convert.ToInt32(GetConfigValue(config["maxInvalidPasswordAttempts"], "5")); this.passwordAttemptWindow = Convert.ToInt32(GetConfigValue(config["passwordAttemptWindow"], "10")); this.minRequiredNonalphanumericCharacters = Convert.ToInt32(GetConfigValue(config["minRequiredNonalphanumericCharacters"], "1")); this.minRequiredPasswordLength = Convert.ToInt32(GetConfigValue(config["minRequiredPasswordLength"], "6")); this.enablePasswordReset = Convert.ToBoolean(GetConfigValue(config["enablePasswordReset"], "true")); this.enablePasswordRetrieval = Convert.ToBoolean(GetConfigValue(config["enablePasswordRetrieval"], "false")); this.passwordStrengthRegularExpression = Convert.ToString(GetConfigValue(config["passwordStrengthRegularExpression"], "")); this.requiresUniqueEmail = Convert.ToBoolean(GetConfigValue(config["requiresUniqueEmail"], "true")); this.passwordFormat = (MembershipPasswordFormat)Enum.Parse(typeof(MembershipPasswordFormat), GetConfigValue(config["passwordFormat"], MembershipPasswordFormat.Clear.ToString())); }
public override void Initialize(string name, NameValueCollection config) { if (config == null) throw new ArgumentException("config"); if (String.IsNullOrEmpty(name)) name = DEFAULT_PROVIDER_NAME; base.Initialize(name, config); applicationName = ConfigurationHelper.GetConfigStringValueOrDefault(config, ConfigurationHelper.CONFIG_APPLICATION_NAME_FIELD, System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath); description = ConfigurationHelper.GetConfigStringValueOrDefault(config, ConfigurationHelper.CONFIG_DESCRIPTION_FIELD, "Couch DB Membership Provider"); enablePasswordReset = ConfigurationHelper.GetConfigBoolValueOrDefault(config, ConfigurationHelper.CONFIG_ENABLE_PASSWORD_RESET, false); enablePasswordRetrieval = false; maxInvalidPasswordAttempts = ConfigurationHelper.GetConfigIntValueOrDefault(config, ConfigurationHelper.CONFIG_MAX_INVALID_PASSWORD_ATTEMPTS, 5); minRequiredNonAlphanumericCharacters = ConfigurationHelper.GetConfigIntValueOrDefault(config, ConfigurationHelper.CONFIG_MIN_REQUIRED_NON_ALPHANUMERIC_CHARACTERS, 0); minRequiredPasswordLength = ConfigurationHelper.GetConfigIntValueOrDefault(config, ConfigurationHelper.CONFIG_MIN_REQUIRED_PASSWORD_LENGTH, 8); passwordAttemptWindow = ConfigurationHelper.GetConfigIntValueOrDefault(config, ConfigurationHelper.CONFIG_PASSWORD_ATTEMPT_WINDOW, 10); passwordFormat = MembershipPasswordFormat.Hashed; passwordStrengthRegularExpression = ConfigurationHelper.GetConfigStringValueOrDefault(config, ConfigurationHelper.CONFIG_PASSWORD_STRENGTH_REGULAR_EXPRESSION, String.Empty); requiresQuestionAndAnswer = ConfigurationHelper.GetConfigBoolValueOrDefault(config, ConfigurationHelper.CONFIG_REQUIRES_QUESTION_AND_ANSWER, false); requiresUniqueEmail = true; providerName = name; couchDbServerName = ConfigurationHelper.MembershipCouchDbServerName; couchDbServerPort = ConfigurationHelper.MembershipCouchDbServerPort; couchDbDatabaseName = ConfigurationHelper.MembershipCouchDbDatabaseName; if (String.IsNullOrEmpty(couchDbDatabaseName)) throw new ProviderException(Strings.CouchDbConfigurationDatabaseNameMissing); machineKeySection = (MachineKeySection)WebConfigurationManager.GetWebApplicationSection("system.web/machineKey"); if(machineKeySection == null) throw new ProviderException(Strings.HashedPasswordsRequireMachineKey); if (machineKeySection.ValidationKey.ToLower().Contains("Autogenerate".ToLower())) throw new ProviderException(Strings.HashedPasswordsRequireMachineKey); }
/// <summary> /// Initializes the repository. /// </summary> /// <param name="name">The friendly name of the repository.</param> /// <param name="config">A collection of the name/value pairs representing the repository-specific attributes specified in the configuration for this repository.</param> /// <exception cref="T:System.ArgumentNullException"> /// The name of the repository is null. /// </exception> /// <exception cref="T:System.ArgumentException"> /// The name of the repository has a length of zero. /// </exception> /// <exception cref="T:System.InvalidOperationException"> /// An attempt is made to call <see cref="M:System.Configuration.Provider.ProviderBase.Initialize(System.String,System.Collections.Specialized.NameValueCollection)"/> on a repository after the repository has already been initialized. /// </exception> public override void Initialize(string name, NameValueCollection config) { if (config == null) { throw new ArgumentNullException("config"); } var provider = GetStringConfigValue(config, "userRepository", string.Empty); userRepository = userRepositoryManager.GetRepository(provider); appName = GetStringConfigValue(config, "applicationName", userRepository.Name); providerName = !string.IsNullOrEmpty(name) ? name : userRepository.Name; base.Initialize(providerName, config); requiresUniqueEmail = GetBooleanConfigValue(config, "requiresUniqueEmail", false); requiresQuestionAndAnswer = GetBooleanConfigValue(config, "requiresQuestionAndAnswer", false); passwordAttemptWindow = GetIntegerConfigValue(config, "passwordAttemptWindow", 10); minRequiredPasswordLength = GetIntegerConfigValue(config, "minRequiredPasswordLength", 7); minRequiredNonAlphanumericCharacters = GetIntegerConfigValue(config, "minRequiredNonalphanumericCharacters", 1); maxInvalidPasswordAttempts = GetIntegerConfigValue(config, "maxInvalidPasswordAttempts", 5); enablePasswordReset = GetBooleanConfigValue(config, "enablePasswordReset", false); enablePasswordRetrieval = GetBooleanConfigValue(config, "enablePasswordRetrieval", false); passwordStrengthRegularExpression = GetStringConfigValue(config, "passwordStrengthRegularExpression", string.Empty); passwordFormat = (MembershipPasswordFormat) Enum.Parse(typeof(MembershipPasswordFormat), GetStringConfigValue(config, "passwordFormat", "Hashed")); }
/// <summary> /// The encrypt password. /// </summary> /// <param name="pass"> /// The pass. /// </param> /// <param name="passwordFormat"> /// The password format. /// </param> /// <param name="salt"> /// The salt. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> private static string EncryptPassword(string pass, MembershipPasswordFormat passwordFormat, string salt) { var hashAlgorithmType = HashHelper.HashAlgorithmType.SHA1; try { Membership.HashAlgorithmType.ToEnum <HashHelper.HashAlgorithmType>(); } catch (Exception exception) { hashAlgorithmType = HashHelper.HashAlgorithmType.SHA1; } switch (passwordFormat) { case MembershipPasswordFormat.Clear: return(pass); case MembershipPasswordFormat.Hashed: return(HashHelper.Hash( pass, hashAlgorithmType, salt, false, HashHelper.HashCaseType.None, null, false)); case MembershipPasswordFormat.Encrypted: var passwordManager = new YafMembershipProvider(); return(passwordManager.GetClearTextPassword(pass)); } return(pass); }
public bool CheckPassword(string password, string dbpassword, MembershipPasswordFormat passwordFormat) { string pass1 = password; string pass2 = dbpassword; switch (passwordFormat) { case MembershipPasswordFormat.Encrypted: pass2 = _passwordEncoder.UnEncodePassword(dbpassword); break; case MembershipPasswordFormat.Hashed: pass1 = _passwordEncoder.EncodePassword(password); break; default: break; } if (pass1 == pass2) { return(true); } return(false); }
/// <summary> /// Initializes the provider. /// </summary> /// <param name="name">The friendly name of the provider.</param> /// <param name="config">A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider.</param> /// <exception cref="T:System.ArgumentNullException"> /// The name of the provider is null. /// </exception> /// <exception cref="T:System.ArgumentException"> /// The name of the provider has a length of zero. /// </exception> /// <exception cref="T:System.InvalidOperationException"> /// An attempt is made to call <see cref="M:System.Configuration.Provider.ProviderBase.Initialize(System.String,System.Collections.Specialized.NameValueCollection)"/> on a provider after the provider has already been initialized. /// </exception> public override void Initialize(string name, NameValueCollection config) { base.Initialize(name, config); string defaultAppName = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath; ApplicationName = config.GetString("applicationName", defaultAppName); // fetch provider settings _enablePasswordReset = config.GetBool("enablePasswordReset", true); _enablePasswordRetrieval = config.GetBool("enablePasswordRetrieval", false); _maxInvalidPasswordAttempts = config.GetInt("maxInvalidPasswordAttempts", 5); _minRequiredNonAlphanumericCharacters = config.GetInt("minRequiredNonAlphanumericCharacters", 0); _minRequiredPasswordLength = config.GetInt("minRequiredPasswordLength", 4); _passwordAttemptWindow = config.GetInt("passwordAttemptWindow", 10); _passwordFormat = config.GetEnum <MembershipPasswordFormat>("passwordFormat"); _passwordStrengthRegularExpression = config.GetString("passwordStrengthRegularExpression", @"[\w| !§$%&/()=\-?\*]*"); _requiresQuestionAndAnswer = config.GetBool("requiresQuestionAndAnswer", false); _requiresUniqueEmail = config.GetBool("requiresUniqueEmail", true); CaseSensitive = config.GetBool("caseSensitive", false); Comparer = CaseSensitive ? StringComparer.CurrentCulture : StringComparer.CurrentCultureIgnoreCase; Comparison = CaseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase; UseUniversalTime = config.GetBool("useUniversalTime", false); }
private void CreateUserWithFormat(MembershipPasswordFormat format) { provider = new MySQLMembershipProvider(); NameValueCollection config = new NameValueCollection(); config.Add("connectionStringName", "LocalMySqlServer"); config.Add("applicationName", "/"); config.Add("passwordStrengthRegularExpression", "bar.*"); config.Add("passwordFormat", format.ToString()); provider.Initialize(null, config); // create the user MembershipCreateStatus status; provider.CreateUser("foo", "barbar!", "*****@*****.**", null, null, true, null, out status); Assert.Equal(MembershipCreateStatus.Success, status); // verify that the password format is hashed. DataTable table = FillTable("SELECT * FROM my_aspnet_membership"); MembershipPasswordFormat rowFormat = (MembershipPasswordFormat)Convert.ToInt32(table.Rows[0]["PasswordFormat"]); Assert.Equal(format, rowFormat); // then attempt to verify the user Assert.True(provider.ValidateUser("foo", "barbar!")); }
private void SetPasswordFormat(string passwordFormat) { if (passwordFormat == null) { passwordFormat = "CLEAR"; } switch (passwordFormat.ToUpper()) { case "HASHED": _passwordFormat = MembershipPasswordFormat.Hashed; break; case "ENCRYPTED": _passwordFormat = MembershipPasswordFormat.Encrypted; break; case "CLEAR": _passwordFormat = MembershipPasswordFormat.Clear; break; default: throw new ProviderException("Password format not supported."); } }
private bool CheckPassword(NotificatorEntities db, string username, string password, bool updateLastLoginActivityDate, bool failIfNotApproved, out string salt, out int passwordFormat, out User usr) { var user = GetDBUser(db, username); usr = user; if (user == null) { salt = null; passwordFormat = -1; return(false); } var enc = EncodePassword(password, user.PasswordFormat, user.PasswordSalt); passwordFormat = user.PasswordFormat; salt = user.PasswordSalt; if (enc == user.Password) { if (updateLastLoginActivityDate) { user.LastActivityDate = DateTime.Now; user.LastLoginDate = DateTime.Now; db.SaveChanges(); } return(true); } else { return(false); } }
public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config) { // Initialize the abstract base class. this.applicationName = config["applicationName"]; if (string.IsNullOrEmpty(this.applicationName)) { this.applicationName = "/"; } this.enablePasswordRetrieval = ProviderUtility.GetBooleanValue(config, "enablePasswordRetrieval", false); this.enablePasswordReset = ProviderUtility.GetBooleanValue(config, "enablePasswordReset", true); this.requiresQuestionAndAnswer = ProviderUtility.GetBooleanValue(config, "requiresQuestionAndAnswer", true); this.requiresUniqueEmail = ProviderUtility.GetBooleanValue(config, "requiresUniqueEmail", true); this.maxInvalidPasswordAttempts = ProviderUtility.GetIntValue(config, "maxInvalidPasswordAttempts", 5, false, 0); this.passwordAttemptWindow = ProviderUtility.GetIntValue(config, "passwordAttemptWindow", 10, false, 0); this.minRequiredPasswordLength = ProviderUtility.GetIntValue(config, "minRequiredPasswordLength", 7, false, 0x80); this.minRequiredNonAlphanumericCharacters = ProviderUtility.GetIntValue(config, "minRequiredNonalphanumericCharacters", 1, true, 0x80); this.passwordStrengthRegularExpression = config["passwordStrengthRegularExpression"]; if (config["passwordFormat"] != null) { this.passwordFormat = (MembershipPasswordFormat)Enum.Parse(typeof(MembershipPasswordFormat), config["passwordFormat"]); } else { this.passwordFormat = MembershipPasswordFormat.Hashed; } this.remoteProviderName = config["remoteProviderName"]; base.Initialize(name, config); }
private string EncodePassword(string password, MembershipPasswordFormat membershipPasswordFormat, string salt) { if (password == null) { return(null); } if (membershipPasswordFormat == MembershipPasswordFormat.Clear) { return(password); } var passwordBytes = password.ToByteArray(); var saltBytes = Convert.FromBase64String(salt); var allBytes = new byte[saltBytes.Length + passwordBytes.Length]; Buffer.BlockCopy(saltBytes, 0, allBytes, 0, saltBytes.Length); Buffer.BlockCopy(passwordBytes, 0, allBytes, saltBytes.Length, passwordBytes.Length); if (membershipPasswordFormat == MembershipPasswordFormat.Hashed) { return(allBytes.ComputeHash().ToBase64String()); } return(EncryptPassword(allBytes).ToBase64String()); }
public SystemProperties(string applicationName, bool enablePasswordReset, bool enablePasswordRetrieval, int maxInvalidPasswordAttempts, int minRequiredNonAlphanumericCharacters, int minRequiredPasswordLength, int passwordAttemptWindow, MembershipPasswordFormat passwordFormat, string passwordStrengthRegularExpression, bool requiresQuestionAndAnswer, bool requiresUniqueEmail, string connectionName, int userIsOnlineTimeWindow, MachineKeySection machineKey) { _applicationName = applicationName; _enablePasswordReset = enablePasswordReset; _enablePasswordRetrieval = enablePasswordRetrieval; _maxInvalidPasswordAttempts = maxInvalidPasswordAttempts; _minRequiredNonAlphanumericCharacters = minRequiredNonAlphanumericCharacters; _minRequiredPasswordLength = minRequiredPasswordLength; _passwordAttemptWindow = passwordAttemptWindow; _passwordFormat = passwordFormat; _passwordStrengthRegularExpression = passwordStrengthRegularExpression; _requiresQuestionAndAnswer = requiresQuestionAndAnswer; _requiresUniqueEmail = requiresUniqueEmail; _connectionName = connectionName; _machineKey = machineKey; }
/// <summary> /// Creates the membership user. /// </summary> /// <param name="userName">Name of the user.</param> /// <param name="password">The password.</param> /// <param name="emailAddress">The email address.</param> /// <param name="passwordQuestion">The password question.</param> /// <param name="passwordAnswer">The password answer.</param> /// <param name="isApproved">if set to <c>true</c> [is approved].</param> /// <param name="passwordFormat">The password format.</param> /// <returns></returns> /// <exception cref="ParameterNullException">userName /// or /// password /// or /// passwordQuestion /// or /// passwordAnswer</exception> /// <exception cref="System.ArgumentNullException">userName /// or /// password /// or /// passwordQuestion /// or /// passwordAnswer</exception> public IMembership CreateMembershipUser(string userName, string password, string emailAddress, string passwordQuestion, string passwordAnswer, bool isApproved, MembershipPasswordFormat passwordFormat) { if (string.IsNullOrEmpty(userName)) { throw new ParameterNullException("userName"); } if (string.IsNullOrEmpty(password)) { throw new ParameterNullException("password"); } if (string.IsNullOrEmpty(passwordQuestion)) { throw new ParameterNullException("passwordQuestion"); } if (string.IsNullOrEmpty(passwordAnswer)) { throw new ParameterNullException("passwordAnswer"); } IMembership membership = this.membershipFactory.Create(password, isApproved, passwordQuestion, passwordAnswer, passwordFormat); var newMembership = this.membershipRepository.Add(membership, userName); return newMembership; }
public override void Initialize(string name, NameValueCollection config) { base.Initialize(name, config); _EnablePasswordReset = GetConfigValue <bool>(config["enablePasswordReset"], _EnablePasswordReset); _EnablePasswordRetrieval = GetConfigValue <bool>(config["enablePasswordRetrieval"], _EnablePasswordRetrieval); _MaxInvalidPasswordAttempts = GetConfigValue <int>(config["maxInvalidPasswordAttempts"], _MaxInvalidPasswordAttempts); _MinRequiredNonAlphanumericCharacters = GetConfigValue <int>(config["minRequiredNonAlphanumericCharacters"], _MinRequiredNonAlphanumericCharacters); _MinRequiredPasswordLength = GetConfigValue <int>(config["minRequiredPasswordLength"], _MinRequiredPasswordLength); _PasswordAttemptWindow = GetConfigValue <int>(config["passwordAttemptWindow"], _PasswordAttemptWindow); if (config["passwordFormat"] != null) { _PasswordFormat = (MembershipPasswordFormat)Enum.Parse(typeof(MembershipPasswordFormat), config["passwordFormat"], true); } _PasswordStrengthRegularExpression = GetConfigValue <string>(config["passwordStrengthRegularExpression"], _PasswordStrengthRegularExpression); _RequiresQuestionAndAnswer = GetConfigValue <bool>(config["requiresQuestionAndAnswer"], _RequiresQuestionAndAnswer); _RequiresUniqueEmail = GetConfigValue <bool>(config["requiresUniqueEmail"], _RequiresUniqueEmail); _RequiresIsApprovedForValidate = GetConfigValue <bool>(config["requiresIsApprovedForValidate"], _RequiresIsApprovedForValidate); UserStorageServiceName = GetConfigValue <string>(config["userStorageServiceName"], UserStorageServiceName); PasswordEncrypterServiceName = GetConfigValue <string>(config["encrypterServiceName"], PasswordEncrypterServiceName); }
public static string EncodePassword(int userPasswordFormat, string password, string validationKey) { MembershipPasswordFormat passwordFormat = (MembershipPasswordFormat)userPasswordFormat; string str = password; switch (passwordFormat) { case MembershipPasswordFormat.Clear: return(str); case MembershipPasswordFormat.Hashed: { return(str); //if (string.IsNullOrEmpty(validationKey)) //{ // validationKey = machineKey.ValidationKey; //} //var hmacsha = new HMACSHA1 { Key = HexToByte(validationKey) }; //return Convert.ToBase64String(hmacsha.ComputeHash(Encoding.Unicode.GetBytes(password))); } case MembershipPasswordFormat.Encrypted: return(str); //return Convert.ToBase64String(EncryptPassword(Encoding.Unicode.GetBytes(password))); } return(str); }
internal string EncodePassword(string password, MembershipPasswordFormat passwordFormat, string key) { string encodedPassword = password; switch (passwordFormat) { case MembershipPasswordFormat.Clear: throw new ProviderException(Strings.UnsupportedPasswordFormat); case MembershipPasswordFormat.Encrypted: throw new ProviderException(Strings.UnsupportedPasswordFormat); case MembershipPasswordFormat.Hashed: var hash = new HMACSHA1(); hash.Key = HexToByte(key); encodedPassword = Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password))); break; default: throw new ProviderException(Strings.UnsupportedPasswordFormat); } return(encodedPassword); }
private string EncodePassword(string password, MembershipPasswordFormat membershipPasswordFormat, string salt) { if (password == null) { return(null); } if (membershipPasswordFormat == MembershipPasswordFormat.Clear) { return(password); } var passwordBytes = Encoding.Unicode.GetBytes(password); var saltBytes = Convert.FromBase64String(salt); var allBytes = new byte[saltBytes.Length + passwordBytes.Length]; Buffer.BlockCopy(saltBytes, 0, allBytes, 0, saltBytes.Length); Buffer.BlockCopy(passwordBytes, 0, allBytes, saltBytes.Length, passwordBytes.Length); if (membershipPasswordFormat == MembershipPasswordFormat.Hashed) { return(Convert.ToBase64String(HashAlgorithm.Create("SHA1").ComputeHash(allBytes))); } return(Convert.ToBase64String(EncryptPassword(allBytes))); }
public static string EncodePassword(MembershipPasswordFormat format, string cleanString, string salt) { byte[] bytes = Encoding.UTF8.GetBytes(salt + cleanString); string result; switch (format) { case MembershipPasswordFormat.Clear: result = cleanString; break; case MembershipPasswordFormat.Hashed: { byte[] value = ((HashAlgorithm)CryptoConfig.CreateFromName("SHA1")).ComputeHash(bytes); result = BitConverter.ToString(value); break; } default: { byte[] value = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(bytes); result = BitConverter.ToString(value); break; } } return(result); }
public static string Encode(string pass, MembershipPasswordFormat passwordFormat, string salt) { if (passwordFormat == MembershipPasswordFormat.Clear) // MembershipPasswordFormat.Clear { return(pass); } byte[] bIn = Encoding.Unicode.GetBytes(pass); byte[] bSalt = Convert.FromBase64String(salt); byte[] bAll = new byte[bSalt.Length + bIn.Length]; byte[] bRet = null; Buffer.BlockCopy(bSalt, 0, bAll, 0, bSalt.Length); Buffer.BlockCopy(bIn, 0, bAll, bSalt.Length, bIn.Length); if (passwordFormat == MembershipPasswordFormat.Hashed) { // MembershipPasswordFormat.Hashed HashAlgorithm s = HashAlgorithm.Create(Membership.HashAlgorithmType); bRet = s.ComputeHash(bAll); } else { bRet = EncryptPassword(bAll); } return(Convert.ToBase64String(bRet)); }
public override void Initialize(string name, NameValueCollection config) { this.ApplicationName = config["applicationName"] ?? HostingEnvironment.ApplicationVirtualPath; this.enablePasswordReset = Boolean.Parse(config["enablePasswordReset"] ?? "true"); this.enablePasswordRetrieval = Boolean.Parse(config["enablePasswordRetrieval"] ?? "false"); this.maxInvalidPasswordAttempts = Int32.Parse(config["maxInvalidPasswordAttempts"] ?? "5"); this.minRequiredNonAlphanumericCharacters = Int32.Parse(config["minRequiredNonAlphanumericCharacters"] ?? "1"); this.minRequiredPasswordLength = Int32.Parse(config["minRequiredPasswordLength"] ?? "7"); this.passwordAttemptWindow = Int32.Parse(config["passwordAttemptWindow"] ?? "10"); this.passwordFormat = (MembershipPasswordFormat)Enum.Parse(typeof(MembershipPasswordFormat), config["passwordFormat"] ?? "Hashed"); this.passwordStrengthRegularExpression = config["passwordStrengthRegularExpression"] ?? String.Empty; this.requiresQuestionAndAnswer = Boolean.Parse(config["requiresQuestionAndAnswer"] ?? "false"); this.requiresUniqueEmail = Boolean.Parse(config["requiresUniqueEmail"] ?? "true"); if (this.PasswordFormat == MembershipPasswordFormat.Hashed && this.EnablePasswordRetrieval) { throw new ProviderException("Configured settings are invalid: Hashed passwords cannot be retrieved. Either set the password format to different type, or set enablePasswordRetrieval to false."); } this.mongoCollection = ConnectionHelper.GetDatabase(config).GetCollection(config["collection"] ?? "Users"); this.mongoCollection.EnsureIndex("ApplicationName"); this.mongoCollection.EnsureIndex("ApplicationName", "Email"); this.mongoCollection.EnsureIndex("ApplicationName", "Username"); this.mongoCollection.EnsureIndex(IndexKeys.Ascending("ApplicationName", "Username"), IndexOptions.SetUnique(true).SetName("UniqueApplicationNameUserName")); base.Initialize(name, config); }
private void CreateUserWithFormat(MembershipPasswordFormat format) { NameValueCollection config = new NameValueCollection(); config.Add("connectionStringName", _connStrName); config.Add("applicationName", _applicationName); config.Add("passwordStrengthRegularExpression", "bar.*"); config.Add("passwordFormat", format.ToString()); provider.Initialize(null, config); // create the user MembershipCreateStatus status; provider.CreateUser("foo", "barbar!", "*****@*****.**", null, null, true, null, out status); Assert.AreEqual(MembershipCreateStatus.Success, status); // verify that the password format was saved var user = _db.GetCollection <User>(provider.CollectionName).FindOne(Query.EQ(provider.ElementNames.LowercaseUsername, "foo")); MembershipPasswordFormat rowFormat = user.PasswordFormat; Assert.AreEqual(format, rowFormat); // then attempt to verify the user Assert.IsTrue(provider.ValidateUser("foo", "barbar!")); }
public override void Initialize(string name, NameValueCollection config) { ApplicationName = config["applicationName"].ConvertOrDefault(HostingEnvironment.ApplicationVirtualPath); enablePasswordReset = config["enablePasswordReset"].ConvertOrDefault(true); enablePasswordRetrieval = config["enablePasswordRetrieval"].ConvertOrDefault(false); maxInvalidPasswordAttempts = config["maxInvalidPasswordAttempts"].ConvertOrDefault(5); minRequiredNonAlphanumericCharacters = config["minRequiredNonAlphanumericCharacters"].ConvertOrDefault(1); minRequiredPasswordLength = config["minRequiredPasswordLength"].ConvertOrDefault(7); passwordAttemptWindow = config["passwordAttemptWindow"].ConvertOrDefault(10); passwordFormat = config["passwordFormat"].ConvertOrDefault(MembershipPasswordFormat.Hashed); passwordStrengthRegularExpression = config["passwordStrengthRegularExpression"].ConvertOrDefault(string.Empty); requiresQuestionAndAnswer = config["requiresQuestionAndAnswer"].ConvertOrDefault(false); requiresUniqueEmail = config["requiresUniqueEmail"].ConvertOrDefault(true); MongoConnectionString = Util.GetConnectionStringByName(config["connectionStringKeys"].ConvertOrDefault(string.Empty)); mongoGateway = new MongoGateway(MongoConnectionString); if (PasswordFormat == MembershipPasswordFormat.Hashed && EnablePasswordRetrieval) { throw new ProviderException("Configured settings are invalid: Hashed passwords cannot be retrieved. Either set the password format to different type, or set enablePasswordRetrieval to false."); } base.Initialize(name, config); }
public static string UnEncodePassword(MembershipPasswordFormat passwordFormat, string encodedPassword) { string password = encodedPassword; switch (passwordFormat) { case MembershipPasswordFormat.Clear: break; case MembershipPasswordFormat.Encrypted: //password = // Encoding.Unicode.GetString(DecryptPassword(Convert.FromBase64String(password))); password = Encoding.Unicode.GetString(Convert.FromBase64String(password)); break; case MembershipPasswordFormat.Hashed: throw new ProviderException("Cannot unencode a hashed password."); default: throw new ProviderException("Unsupported password format."); } return(password); }
public void PasswordFormatTest_should_return_encrypted_from_config() { _provider.Initialize("RavenTest", CreateConfigFake()); MembershipPasswordFormat passFormat = _provider.PasswordFormat; Assert.AreEqual(MembershipPasswordFormat.Encrypted, passFormat); }
public PasswordSettings(IPasswordResetRetrievalSettings resetOrRetrieval, int minimumLength, int minimumNonAlphanumericCharacters, string regularExpressionToMatch, MembershipPasswordFormat storageFormat) { ResetOrRetrieval = resetOrRetrieval; MinimumLength = minimumLength; MinimumNonAlphanumericCharacters = minimumNonAlphanumericCharacters; RegularExpressionToMatch = regularExpressionToMatch; StorageFormat = storageFormat; }
public override void Initialize(string name, NameValueCollection config) { if (config.IsNull()) { throw new ArgumentNullException("config"); } if (name.IsNullOrEmpty()) { name = "MongoMembershipProvider"; } if (config["description"].IsNullOrEmpty()) { config.Remove("description"); config.Add("description", "MongoDB Membership provider"); } base.Initialize(name, config); ApplicationName = getConfigValue(config["applicationName"], System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath); pMaxInvalidPasswordAttempts = Convert.ToInt32(getConfigValue(config["maxInvalidPasswordAttempts"], "5")); pPasswordAttemptWindow = Convert.ToInt32(getConfigValue(config["passwordAttemptWindow"], "10")); pMinRequiredNonAlphanumericCharacters = Convert.ToInt32(getConfigValue(config["minRequiredNonAlphanumericCharacters"], "1")); pMinRequiredPasswordLength = Convert.ToInt32(getConfigValue(config["minRequiredPasswordLength"], "7")); pPasswordStrengthRegularExpression = Convert.ToString(getConfigValue(config["passwordStrengthRegularExpression"], "")); pEnablePasswordReset = Convert.ToBoolean(getConfigValue(config["enablePasswordReset"], "true")); pEnablePasswordRetrieval = Convert.ToBoolean(getConfigValue(config["enablePasswordRetrieval"], "true")); pRequiresQuestionAndAnswer = Convert.ToBoolean(getConfigValue(config["requiresQuestionAndAnswer"], "false")); pRequiresUniqueEmail = Convert.ToBoolean(getConfigValue(config["requiresUniqueEmail"], "true")); encryptionKey = HexToByte(getConfigValue(config["encryptionKey"], "ABCDEEA2EFAA00B42A")); string password_format = config["passwordFormat"]; if (password_format.IsNullOrEmpty()) { password_format = "Hashed"; } switch (password_format) { case "Hashed": pPasswordFormat = MembershipPasswordFormat.Hashed; break; case "Encrypted": pPasswordFormat = MembershipPasswordFormat.Encrypted; break; case "Clear": pPasswordFormat = MembershipPasswordFormat.Clear; break; default: throw new Exception(String.Format("PasswordFormatNotSupportedMessage")); } }
public void VerifyPasswordTest(string password, MembershipPasswordFormat format) { string salt; var encoded = password.Encode(out salt, format); var result = password.VerifyPassword(encoded, format, salt); result.Should().BeTrue(); }
private string getValidationKey(MembershipPasswordFormat passwordFormat) { // Get encryption and decryption key information from the configuration. Configuration cfg = WebConfigurationManager.OpenWebConfiguration(HostingEnvironment.ApplicationVirtualPath); var machineKey = (MachineKeySection)cfg.GetSection("system.web/machineKey"); if (machineKey.ValidationKey.Contains("AutoGenerate")) if (passwordFormat != MembershipPasswordFormat.Clear) throw new ProviderException("Hashed or Encrypted passwords " + "are not supported with auto-generated keys."); return machineKey.ValidationKey; }
/// <summary> /// Initializes a new <see cref="SqlMembershipProviderPasswordService"/> using the provided password format. /// </summary> /// <param name="passwordFormat">The password encryption method.</param> public SqlMembershipProviderPasswordService(MembershipPasswordFormat passwordFormat) { this.passwordFormat = passwordFormat; this.provider = new SqlMembershipProvider(); var config = new NameValueCollection { { "minRequiredPasswordLength", "1" }, { "minRequiredNonalphanumericCharacters", "0" }, { "passwordFormat", passwordFormat.ToString() }, { "passwordCompatMode", "Framework40" }, { "connectionString" , "__foo__" } }; this.provider.Initialize(null, config); }
public static string EncodePassword(MembershipPasswordFormat format, string cleanString, string salt) { byte[] bytes = Encoding.UTF8.GetBytes(salt.ToLower() + cleanString); switch (format) { case MembershipPasswordFormat.Clear: return cleanString; case MembershipPasswordFormat.Hashed: return BitConverter.ToString(((HashAlgorithm)CryptoConfig.CreateFromName("SHA1")).ComputeHash(bytes)); } return BitConverter.ToString(((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(bytes)); }
public static string EncodePassword(string salt, string password, MembershipPasswordFormat passwordFormat = MembershipPasswordFormat.Hashed) { switch (passwordFormat) { case MembershipPasswordFormat.Clear: return password; case MembershipPasswordFormat.Hashed: byte[] bytes = Encoding.Unicode.GetBytes(salt.ToLower() + password); byte[] inArray = null; HashAlgorithm algorithm = HashAlgorithm.Create(Membership.HashAlgorithmType); inArray = algorithm.ComputeHash(bytes); return Convert.ToBase64String(inArray); default: throw new NotSupportedException(String.Format("PasswordFormat is [{0}]", passwordFormat)); } }
public override void Initialize(string name, NameValueCollection config) { // // Initialize values from web.config. // // Initialize the abstract base class. base.Initialize(name, config); _applicationName = GetConfigValue(config["applicationName"], System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath); _maxInvalidPasswordAttempts = Convert.ToInt32(GetConfigValue(config["maxInvalidPasswordAttempts"], "5")); _passwordAttemptWindow = Convert.ToInt32(GetConfigValue(config["passwordAttemptWindow"], "10")); _minRequiredNonAlphanumericCharacters = Convert.ToInt32(GetConfigValue(config["minRequiredNonAlphanumericCharacters"], "1")); _minRequiredPasswordLength = Convert.ToInt32(GetConfigValue(config["minRequiredPasswordLength"], "7")); _passwordStrengthRegularExpression = Convert.ToString(GetConfigValue(config["passwordStrengthRegularExpression"], "")); _enablePasswordReset = Convert.ToBoolean(GetConfigValue(config["enablePasswordReset"], "true")); _enablePasswordRetrieval = Convert.ToBoolean(GetConfigValue(config["enablePasswordRetrieval"], "true")); _requiresQuestionAndAnswer = Convert.ToBoolean(GetConfigValue(config["requiresQuestionAndAnswer"], "false")); _requiresUniqueEmail = Convert.ToBoolean(GetConfigValue(config["requiresUniqueEmail"], "true")); string tempFormat = config["passwordFormat"]; if (tempFormat == null) { tempFormat = "Hashed"; } switch (tempFormat) { case "Hashed": _passwordFormat = MembershipPasswordFormat.Hashed; break; case "Encrypted": _passwordFormat = MembershipPasswordFormat.Encrypted; break; case "Clear": _passwordFormat = MembershipPasswordFormat.Clear; break; default: throw new ProviderException("Password format not supported."); } // // Initialize OdbcConnection. // }
public static String Decrypt(String encryptedValue, MembershipPasswordFormat format) { String decryptedValue = null; switch (format) { case MembershipPasswordFormat.Encrypted: CryptoManager cryptoManager = new CryptoManager(); decryptedValue = cryptoManager.Decrypt(encryptedValue); break; case MembershipPasswordFormat.Hashed: throw new NotSupportedException("Hashed encrypted values cannot be decrypted"); case MembershipPasswordFormat.Clear: decryptedValue = encryptedValue; break; } return decryptedValue; }
public static String Encrypt(String value, MembershipPasswordFormat format) { String encryptedValue = null; switch (format) { case MembershipPasswordFormat.Encrypted: CryptoManager cryptoManager = new CryptoManager(); encryptedValue = cryptoManager.Encrypt(value); break; case MembershipPasswordFormat.Hashed: encryptedValue = SHA1Manager.Encript(value); break; case MembershipPasswordFormat.Clear: encryptedValue = value; break; } return encryptedValue; }
internal string UnEncodePassword(string encodedPassword, MembershipPasswordFormat passwordFormat) { throw new ProviderException(Strings.CanNotUnencodeHashedPassword); //string password = encodedPassword; //switch (passwordFormat) //{ // case MembershipPasswordFormat.Clear: // throw new ProviderException(Strings.UnsupportedPasswordFormat); // case MembershipPasswordFormat.Encrypted: // throw new ProviderException(Strings.UnsupportedPasswordFormat); // case MembershipPasswordFormat.Hashed: // throw new ProviderException(Strings.CanNotUnencodeHashedPassword); // default: // throw new ProviderException(Strings.UnsupportedPasswordFormat); //} //return password; }
public WinNtMembershipProvider() { _strName = "WinNTMembershipProvider"; _strApplicationName = "DefaultApp"; _userDomain = ""; _logonType = 2; // Interactive by default _boolEnablePasswordReset = false; _boolEnablePasswordRetrieval = false; _boolRequiresQuestionAndAnswer = false; _boolRequiresUniqueEMail = false; _intMaxInvalidPasswordAttempts = 3; _intMinRequiredAlphanumericCharacters = 1; _intMinRequiredPasswordLength = 5; _strPasswordStrengthRegularExpression = @"[\w| !§$%&/()=\-?\*]*"; _oPasswordFormat = MembershipPasswordFormat.Clear; }
public CreateUserViewModel CreateUser(string salt, string pass, string encodedPasswordAnswer, string username, string email, string passwordQuestion, object providerUserKey, bool isApproved, bool requiresUniqueEmail, MembershipPasswordFormat passwordFormat) { DateTime dt = DataProviderHelper.RoundToSeconds(DateTime.UtcNow); var cmd = new SqlCommand("dbo.aspnet_Membership_CreateUser", Holder.Connection) { CommandTimeout = CommandTimeout, CommandType = CommandType.StoredProcedure }; cmd.Parameters.Add(DataProviderHelper.CreateInputParam("@ApplicationName", SqlDbType.NVarChar, ApplicationName)); cmd.Parameters.Add(DataProviderHelper.CreateInputParam("@UserName", SqlDbType.NVarChar, username)); cmd.Parameters.Add(DataProviderHelper.CreateInputParam("@Password", SqlDbType.NVarChar, pass)); cmd.Parameters.Add(DataProviderHelper.CreateInputParam("@PasswordSalt", SqlDbType.NVarChar, salt)); cmd.Parameters.Add(DataProviderHelper.CreateInputParam("@Email", SqlDbType.NVarChar, email)); cmd.Parameters.Add(DataProviderHelper.CreateInputParam("@PasswordQuestion", SqlDbType.NVarChar, passwordQuestion)); cmd.Parameters.Add(DataProviderHelper.CreateInputParam("@PasswordAnswer", SqlDbType.NVarChar, encodedPasswordAnswer)); cmd.Parameters.Add(DataProviderHelper.CreateInputParam("@IsApproved", SqlDbType.Bit, isApproved)); cmd.Parameters.Add(DataProviderHelper.CreateInputParam("@UniqueEmail", SqlDbType.Int, requiresUniqueEmail ? 1 : 0)); cmd.Parameters.Add(DataProviderHelper.CreateInputParam("@PasswordFormat", SqlDbType.Int, (int)passwordFormat)); cmd.Parameters.Add(DataProviderHelper.CreateInputParam("@CurrentTimeUtc", SqlDbType.DateTime, dt)); SqlParameter p = DataProviderHelper.CreateInputParam("@UserId", SqlDbType.UniqueIdentifier, providerUserKey); p.Direction = ParameterDirection.InputOutput; cmd.Parameters.Add(p); p = new SqlParameter("@ReturnValue", SqlDbType.Int) { Direction = ParameterDirection.ReturnValue }; cmd.Parameters.Add(p); cmd.ExecuteNonQuery(); var iStatus = ((p.Value != null) ? ((int)p.Value) : -1); if (iStatus < 0 || iStatus > (int)MembershipCreateStatus.ProviderError) iStatus = (int)MembershipCreateStatus.ProviderError; return new CreateUserViewModel { Status = iStatus, UserId = new Guid(cmd.Parameters["@UserId"].Value.ToString()), Date = dt }; }
internal string EncodePassword(string password, MembershipPasswordFormat passwordFormat, string key) { string encodedPassword = password; switch (passwordFormat) { case MembershipPasswordFormat.Clear: throw new ProviderException(Strings.UnsupportedPasswordFormat); case MembershipPasswordFormat.Encrypted: throw new ProviderException(Strings.UnsupportedPasswordFormat); case MembershipPasswordFormat.Hashed: var hash = new HMACSHA1(); hash.Key = HexToByte(key); encodedPassword = Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password))); break; default: throw new ProviderException(Strings.UnsupportedPasswordFormat); } return encodedPassword; }
/// <summary> /// Creates the specified user id. /// </summary> /// <param name="password">The password.</param> /// <param name="isApproved">if set to <c>true</c> [is approved].</param> /// <param name="passwordQuestion">The password question.</param> /// <param name="passwordAnswer">The password answer.</param> /// <param name="passwordFormat">The password format.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">password</exception> public IMembership Create(string password, bool isApproved, string passwordQuestion, string passwordAnswer, MembershipPasswordFormat passwordFormat) { if (string.IsNullOrEmpty(password)) { throw new ParameterNullException("password"); } if (string.IsNullOrEmpty(passwordQuestion)) { throw new ParameterNullException("passwordQuestion"); } if (string.IsNullOrEmpty(passwordAnswer)) { throw new ParameterNullException("passwordAnswer"); } var inverGrovePasswordFormat = passwordFormat.ToInverGrovePasswordFormat(); var membership = new Membership { PasswordSalt = password.GetRandomSalt(), PasswordFormatId = (int)inverGrovePasswordFormat, IsApproved = isApproved, PasswordQuestion = passwordQuestion }; var strippedSecurityAnswer = passwordAnswer.ToSecurityAnswer(); var hashedSecurityAnswer = strippedSecurityAnswer.FormatPasscode(inverGrovePasswordFormat, membership.PasswordSalt); membership.Password = password.FormatPasscode(inverGrovePasswordFormat, membership.PasswordSalt); membership.PasswordAnswer = (inverGrovePasswordFormat == InverGrovePasswordFormat.Hashed) ? hashedSecurityAnswer : strippedSecurityAnswer; membership.FailedPasswordAttemptWindowStart = DateTime.MinValue.IsSqlSafeDate(); membership.FailedPasswordAnswerAttemptWindowStart = DateTime.MinValue.IsSqlSafeDate(); return membership; }
private void CreateUserWithFormat(MembershipPasswordFormat format) { provider = new MySQLMembershipProvider(); NameValueCollection config = new NameValueCollection(); config.Add("connectionStringName", "LocalMySqlServer"); config.Add("applicationName", "/"); config.Add("passwordStrengthRegularExpression", "bar.*"); config.Add("passwordFormat", format.ToString()); provider.Initialize(null, config); // create the user MembershipCreateStatus status; provider.CreateUser("foo", "barbar!", "*****@*****.**", null, null, true, null, out status); Assert.AreEqual(MembershipCreateStatus.Success, status); // verify that the password format is hashed. DataTable table = FillTable("SELECT * FROM my_aspnet_Membership"); MembershipPasswordFormat rowFormat = (MembershipPasswordFormat)Convert.ToInt32(table.Rows[0]["PasswordFormat"]); Assert.AreEqual(format, rowFormat); // then attempt to verify the user Assert.IsTrue(provider.ValidateUser("foo", "barbar!")); }
public static string EncodePassword(string pass, MembershipPasswordFormat passwordFormat, string salt) { if (passwordFormat == MembershipPasswordFormat.Clear) return pass; byte[] bIn = Encoding.Unicode.GetBytes(pass); byte[] bSalt = Convert.FromBase64String(salt); var bAll = new byte[bSalt.Length + bIn.Length]; byte[] bRet; Buffer.BlockCopy(bSalt, 0, bAll, 0, bSalt.Length); Buffer.BlockCopy(bIn, 0, bAll, bSalt.Length, bIn.Length); if (passwordFormat == MembershipPasswordFormat.Hashed) { HashAlgorithm s = HashAlgorithm.Create(Membership.HashAlgorithmType); bRet = s.ComputeHash(bAll); } else { bRet = EncryptPassword(bAll); } return Convert.ToBase64String(bRet); }
public bool CheckPassword(string password, string dbpassword, MembershipPasswordFormat passwordFormat) { string pass1 = password; string pass2 = dbpassword; switch (passwordFormat) { case MembershipPasswordFormat.Encrypted: pass2 = _passwordEncoder.UnEncodePassword(dbpassword); break; case MembershipPasswordFormat.Hashed: pass1 = _passwordEncoder.EncodePassword(password); break; default: break; } if (pass1 == pass2) { return true; } return false; }
////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// public override void Initialize(string name, NameValueCollection config) { HttpRuntime.CheckAspNetHostingPermission (AspNetHostingPermissionLevel.Low, SR.Feature_not_supported_at_this_level); if (config == null) throw new ArgumentNullException("config"); if (String.IsNullOrEmpty(name)) name = "SqlMembershipProvider"; if (string.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", SR.GetString(SR.MembershipSqlProvider_description)); } base.Initialize(name, config); _SchemaVersionCheck = 0; _EnablePasswordRetrieval = SecUtility.GetBooleanValue(config, "enablePasswordRetrieval", false); _EnablePasswordReset = SecUtility.GetBooleanValue(config, "enablePasswordReset", true); _RequiresQuestionAndAnswer = SecUtility.GetBooleanValue(config, "requiresQuestionAndAnswer", true); _RequiresUniqueEmail = SecUtility.GetBooleanValue(config, "requiresUniqueEmail", true); _MaxInvalidPasswordAttempts = SecUtility.GetIntValue( config, "maxInvalidPasswordAttempts", 5, false, 0 ); _PasswordAttemptWindow = SecUtility.GetIntValue( config, "passwordAttemptWindow", 10, false, 0 ); _MinRequiredPasswordLength = SecUtility.GetIntValue( config, "minRequiredPasswordLength", 7, false, 128 ); _MinRequiredNonalphanumericCharacters = SecUtility.GetIntValue( config, "minRequiredNonalphanumericCharacters", 1, true, 128 ); _passwordStrengthRegexTimeout = SecUtility.GetNullableIntValue(config, "passwordStrengthRegexTimeout"); _PasswordStrengthRegularExpression = config["passwordStrengthRegularExpression"]; if( _PasswordStrengthRegularExpression != null ) { _PasswordStrengthRegularExpression = _PasswordStrengthRegularExpression.Trim(); if( _PasswordStrengthRegularExpression.Length != 0 ) { try { Regex regex = new Regex( _PasswordStrengthRegularExpression ); } catch( ArgumentException e ) { throw new ProviderException( e.Message, e ); } } } else { _PasswordStrengthRegularExpression = string.Empty; } if (_MinRequiredNonalphanumericCharacters > _MinRequiredPasswordLength) throw new HttpException(SR.GetString(SR.MinRequiredNonalphanumericCharacters_can_not_be_more_than_MinRequiredPasswordLength)); _CommandTimeout = SecUtility.GetIntValue( config, "commandTimeout", 30, true, 0 ); _AppName = config["applicationName"]; if (string.IsNullOrEmpty(_AppName)) _AppName = SecUtility.GetDefaultAppName(); if( _AppName.Length > 256 ) { throw new ProviderException(SR.GetString(SR.Provider_application_name_too_long)); } string strTemp = config["passwordFormat"]; if (strTemp == null) strTemp = "Hashed"; switch(strTemp) { case "Clear": _PasswordFormat = MembershipPasswordFormat.Clear; break; case "Encrypted": _PasswordFormat = MembershipPasswordFormat.Encrypted; break; case "Hashed": _PasswordFormat = MembershipPasswordFormat.Hashed; break; default: throw new ProviderException(SR.GetString(SR.Provider_bad_password_format)); } if (PasswordFormat == MembershipPasswordFormat.Hashed && EnablePasswordRetrieval) throw new ProviderException(SR.GetString(SR.Provider_can_not_retrieve_hashed_password)); //if (_PasswordFormat == MembershipPasswordFormat.Encrypted && MachineKeySection.IsDecryptionKeyAutogenerated) // throw new ProviderException(SR.GetString(SR.Can_not_use_encrypted_passwords_with_autogen_keys)); _sqlConnectionString = SecUtility.GetConnectionString(config); string temp = config["passwordCompatMode"]; if (!string.IsNullOrEmpty(temp)) _LegacyPasswordCompatibilityMode = (MembershipPasswordCompatibilityMode)Enum.Parse(typeof(MembershipPasswordCompatibilityMode), temp); config.Remove("connectionStringName"); config.Remove("connectionString"); config.Remove("enablePasswordRetrieval"); config.Remove("enablePasswordReset"); config.Remove("requiresQuestionAndAnswer"); config.Remove("applicationName"); config.Remove("requiresUniqueEmail"); config.Remove("maxInvalidPasswordAttempts"); config.Remove("passwordAttemptWindow"); config.Remove("commandTimeout"); config.Remove("passwordFormat"); config.Remove("name"); config.Remove("minRequiredPasswordLength"); config.Remove("minRequiredNonalphanumericCharacters"); config.Remove("passwordStrengthRegularExpression"); config.Remove("passwordCompatMode"); config.Remove("passwordStrengthRegexTimeout"); if (config.Count > 0) { string attribUnrecognized = config.GetKey(0); if (!String.IsNullOrEmpty(attribUnrecognized)) throw new ProviderException(SR.GetString(SR.Provider_unrecognized_attribute, attribUnrecognized)); } }
// // System.Configuration.Provider.ProviderBase.Initialize Method // public override void Initialize(string name, NameValueCollection config) { // // Initialize values from web.config. // if (config == null) throw new ArgumentNullException("config"); if (name == null || name.Length == 0) name = "hMailServerMembershipProvider"; if (String.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", "hMailServer Membership provider"); } // Initialize the abstract base class. base.Initialize(name, config); pApplicationName = GetConfigValue(config["applicationName"], ""); pMaxInvalidPasswordAttempts = Convert.ToInt32(GetConfigValue(config["maxInvalidPasswordAttempts"], "5")); pPasswordAttemptWindow = Convert.ToInt32(GetConfigValue(config["passwordAttemptWindow"], "10")); pMinRequiredNonAlphanumericCharacters = Convert.ToInt32(GetConfigValue(config["minRequiredNonAlphanumericCharacters"], "1")); pMinRequiredPasswordLength = Convert.ToInt32(GetConfigValue(config["minRequiredPasswordLength"], "7")); pPasswordStrengthRegularExpression = Convert.ToString(GetConfigValue(config["passwordStrengthRegularExpression"], "")); pEnablePasswordReset = Convert.ToBoolean(GetConfigValue(config["enablePasswordReset"], "true")); pEnablePasswordRetrieval = false; pRequiresQuestionAndAnswer = false; pRequiresUniqueEmail = true; string temp_format = GetConfigValue(config["passwordFormat"], "Hashed"); switch (temp_format) { case "Hashed": pPasswordFormat = MembershipPasswordFormat.Hashed; break; default: throw new ProviderException("Password format not supported."); } }
/// <summary> /// Initializes the provider. /// </summary> /// <param name="name">The friendly name of the provider.</param> /// <param name="config">A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider.</param> /// <exception cref="T:System.ArgumentNullException">The name of the provider is null.</exception> /// /// <exception cref="T:System.ArgumentException">The name of the provider has a length of zero.</exception> /// /// <exception cref="T:System.InvalidOperationException">An attempt is made to call <see cref="M:System.Configuration.Provider.ProviderBase.Initialize(System.String,System.Collections.Specialized.NameValueCollection)"/> on a provider after the provider has already been initialized.</exception> public override void Initialize(string name, NameValueCollection config) { // // Initialize values from web.config. // if (config == null) throw new ArgumentNullException("config"); if (name == null || name.Length == 0) name = "MongoDBMembershipProvider"; if (String.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", "Sample MongoDB Membership provider"); } // Initialize the abstract base class. base.Initialize(name, config); pApplicationName = GetConfigValue(config["applicationName"], System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath); pMaxInvalidPasswordAttempts = Convert.ToInt32(GetConfigValue(config["maxInvalidPasswordAttempts"], "5")); pPasswordAttemptWindow = Convert.ToInt32(GetConfigValue(config["passwordAttemptWindow"], "10")); pMinRequiredNonAlphanumericCharacters = Convert.ToInt32(GetConfigValue(config["minRequiredNonAlphanumericCharacters"], "1")); pMinRequiredPasswordLength = Convert.ToInt32(GetConfigValue(config["minRequiredPasswordLength"], "7")); pPasswordStrengthRegularExpression = Convert.ToString(GetConfigValue(config["passwordStrengthRegularExpression"], "")); pEnablePasswordReset = Convert.ToBoolean(GetConfigValue(config["enablePasswordReset"], "true")); pEnablePasswordRetrieval = Convert.ToBoolean(GetConfigValue(config["enablePasswordRetrieval"], "true")); pRequiresQuestionAndAnswer = Convert.ToBoolean(GetConfigValue(config["requiresQuestionAndAnswer"], "false")); pRequiresUniqueEmail = Convert.ToBoolean(GetConfigValue(config["requiresUniqueEmail"], "true")); pWriteExceptionsToEventLog = Convert.ToBoolean(GetConfigValue(config["writeExceptionsToEventLog"], "true")); pMongoProviderDatabaseName = Convert.ToString(GetConfigValue(config["mongoProviderDatabaseName"], "ASPNetProviderDB")); pmongoProviderMembershipCollectionName = Convert.ToString(GetConfigValue(config["mongoProviderCollectionName"], "Users")); string temp_format = config["passwordFormat"]; if (temp_format == null) { temp_format = "Hashed"; } switch (temp_format) { case "Hashed": pPasswordFormat = MembershipPasswordFormat.Hashed; break; case "Encrypted": pPasswordFormat = MembershipPasswordFormat.Encrypted; break; case "Clear": pPasswordFormat = MembershipPasswordFormat.Clear; break; default: throw new ProviderException("Password format not supported."); } // // Initialize MongoDB ConnectionString. // ConnectionStringSettings ConnectionStringSettings = ConfigurationManager.ConnectionStrings[config["connectionStringName"]]; if (ConnectionStringSettings == null || ConnectionStringSettings.ConnectionString.Trim() == "") { throw new ProviderException("Connection string cannot be blank."); } connectionString = ConnectionStringSettings.ConnectionString; Configuration cfg = null; if (System.Web.HttpContext.Current != null && !System.Web.HttpContext.Current.Request.PhysicalPath.Equals(string.Empty)) cfg = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~"); //if (Directory.Exists(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath)) // When running from a web app // cfg = WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath); else // when running from a test case. cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); // Get encryption and decryption key information from the configuration. machineKey = (MachineKeySection)cfg.GetSection("system.web/machineKey"); if (machineKey.ValidationKey.Contains("AutoGenerate")) if (PasswordFormat != MembershipPasswordFormat.Clear) throw new ProviderException("Hashed or Encrypted passwords " + "are not supported with auto-generated keys."); // Ensures that the MongoDB collection has the proper indices defined. EnsureIndices(); }
public override void Initialize(string name, NameValueCollection config) { if (config == null) { throw new ArgumentNullException("config"); } if (String.IsNullOrEmpty(name)) { name = "SimpleDbMembershipProvider"; } base.Initialize(name, config); string tempFormat = config["passwordFormat"]; if (tempFormat == null) { tempFormat = "Hashed"; } switch (tempFormat) { case "Hashed": { this._passwordFormat = MembershipPasswordFormat.Hashed; break; } case "Encrypted": { this._passwordFormat = MembershipPasswordFormat.Encrypted; break; } case "Clear": { this._passwordFormat = MembershipPasswordFormat.Clear; break; } } this._simpleDBClient = new AmazonSimpleDBClient( Settings.Default.AWSAccessKey.Trim(), Settings.Default.AWSSecretAccessKey.Trim() ); CreateDomainRequest cdRequest = new CreateDomainRequest() .WithDomainName(Settings.Default.AWSMembershipDomain); try { this._simpleDBClient.CreateDomain(cdRequest); } catch (Exception e) { System.Diagnostics.Debug.Write(String.Concat(e.Message, "\r\n", e.StackTrace)); this.VerifyKeys(); } Configuration cfg = WebConfigurationManager.OpenWebConfiguration(HostingEnvironment.ApplicationVirtualPath); this._machineKey = (MachineKeySection)cfg.GetSection("system.web/machineKey"); }
/// <summary> /// Initializes the provider. /// </summary> /// <param name="name"></param> /// <param name="config"></param> public override void Initialize(string name, NameValueCollection config) { if (config == null) { throw new ArgumentNullException("config"); } if (String.IsNullOrEmpty(name)) { name = "CanonMembershipProvider"; } if (String.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", "Membership provider"); } base.Initialize(name, config); applicationName = GetConfigValue(config["applicationName"], HostingEnvironment.ApplicationVirtualPath); maxInvalidPasswordAttempts = Int32.Parse(GetConfigValue(config["maxInvalidPasswordAttempts"], "5")); passwordAttemptWindow = Int32.Parse(GetConfigValue(config["passwordAttemptWindow"], "10")); minRequiredNonAlphanumericCharacters = Int32.Parse(GetConfigValue(config["minRequiredNonAlphanumericCharacters"], "1")); minRequiredPasswordLength = Int32.Parse(GetConfigValue(config["minRequiredPasswordLength"], "7")); passwordStrengthRegularExpression = GetConfigValue(config["passwordStrengthRegularExpression"], ""); enablePasswordReset = Convert.ToBoolean(GetConfigValue(config["enablePasswordReset"], "true")); enablePasswordRetrieval = Convert.ToBoolean(GetConfigValue(config["enablePasswordRetrieval"], "true")); requiresQuestionAndAnswer = Convert.ToBoolean(GetConfigValue(config["requiresQuestionAndAnswer"], "false")); requiresUniqueEmail = Convert.ToBoolean(GetConfigValue(config["requiresUniqueEmail"], "true")); string tempFormat = config["passwordFormat"] ?? "Hashed"; switch (tempFormat) { case "Hashed": passwordFormat = MembershipPasswordFormat.Hashed; break; case "Encrypted": passwordFormat = MembershipPasswordFormat.Encrypted; break; case "Clear": passwordFormat = MembershipPasswordFormat.Clear; break; default: throw new InvalidOperationException("Password format not supported."); } }
/// <summary> /// Initialize settings the pertain to password hashing / encrypting /// </summary> /// <param name="config"></param> private void InitPasswordEncryptionSettings(NameValueCollection config) { System.Configuration.Configuration cfg = WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath); MachineKeySection machineKey = cfg.GetSection("system.web/machineKey") as MachineKeySection; _hashAlgorithm = machineKey.ValidationAlgorithm; _validationKey = machineKey.ValidationKey; if (_validationKey.Contains("AutoGenerate")) { if (PasswordFormat != MembershipPasswordFormat.Clear) { throw new ProviderException("Hashed or Encrypted passwords are not supported with auto-generated keys."); } } string passFormat = config["passwordFormat"]; if (passFormat == null) { passFormat = "Hashed"; } switch (passFormat) { case "Hashed": _passwordFormat = MembershipPasswordFormat.Hashed; break; case "Encrypted": _passwordFormat = MembershipPasswordFormat.Encrypted; break; case "Clear": _passwordFormat = MembershipPasswordFormat.Clear; break; default: throw new ProviderException("The password format from the custom provider is not supported."); } }
public override void Initialize(string name, NameValueCollection config) { if (config == null) throw new ArgumentNullException("config"); if (name == null || name.Length == 0) name = "IridioMembershipProvider"; if (String.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", "Iridio Membership provider"); } base.Initialize(name, config); ValidatingPassword += IridioMembershipProvider_ValidatingPassword; pApplicationName = GetConfigValue(config["applicationName"], System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath); pMaxInvalidPasswordAttempts = Convert.ToInt32(GetConfigValue(config["maxInvalidPasswordAttempts"], "5")); pPasswordAttemptWindow = Convert.ToInt32(GetConfigValue(config["passwordAttemptWindow"], "10")); pMinRequiredNonAlphanumericCharacters = Convert.ToInt32(GetConfigValue(config["minRequiredNonAlphanumericCharacters"], "1")); pMinRequiredPasswordLength = Convert.ToInt32(GetConfigValue(config["minRequiredPasswordLength"], "7")); pPasswordStrengthRegularExpression = Convert.ToString(GetConfigValue(config["passwordStrengthRegularExpression"], "")); pEnablePasswordReset = Convert.ToBoolean(GetConfigValue(config["enablePasswordReset"], "true")); pEnablePasswordRetrieval = Convert.ToBoolean(GetConfigValue(config["enablePasswordRetrieval"], "true")); pRequiresQuestionAndAnswer = Convert.ToBoolean(GetConfigValue(config["requiresQuestionAndAnswer"], "false")); pRequiresUniqueEmail = Convert.ToBoolean(GetConfigValue(config["requiresUniqueEmail"], "true")); WriteExceptionsToEventLog = Convert.ToBoolean(GetConfigValue(config["writeExceptionsToEventLog"], "true")); string temp_format = config["passwordFormat"]; if (temp_format == null) temp_format = "Clear"; temp_format = temp_format.ToUpper(); switch (temp_format) { case "HASHED": pPasswordFormat = MembershipPasswordFormat.Hashed; break; case "ENCRYPTED": pPasswordFormat = MembershipPasswordFormat.Encrypted; break; case "CLEAR": pPasswordFormat = MembershipPasswordFormat.Clear; break; default: throw new ProviderException("Password's format not supported"); } machineKey = GetMachineKeySection(); if (machineKey.ValidationKey.Contains("AutoGenerate")) if (PasswordFormat != MembershipPasswordFormat.Clear) throw new ProviderException("Hashed or Encrypted passwords do not support autogenerated keys"); SetUserRepository(); }
public override void Initialize(string name, NameValueCollection config) { if (config == null) throw new ArgumentNullException("config"); if (name == null || name.Length == 0) name = "CMSMembershipProvider"; if (String.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", "CMS Membership provider"); } base.Initialize(name, config); pMaxInvalidPasswordAttempts = Convert.ToInt32(GetConfigValue(config["maxInvalidPasswordAttempts"], "5")); pPasswordAttemptWindow = Convert.ToInt32(GetConfigValue(config["passwordAttemptWindow"], "10")); var Db = GetDb(); pMinRequiredPasswordLength = Db.Setting("PasswordMinLength", "7").ToInt(); pMinRequiredNonAlphanumericCharacters = DbUtil.Db.Setting("PasswordRequireSpecialCharacter", "true").ToBool() ? 1 : 0; pPasswordStrengthRegularExpression = Convert.ToString(GetConfigValue(config["passwordStrengthRegularExpression"], "")); pEnablePasswordReset = Convert.ToBoolean(GetConfigValue(config["enablePasswordReset"], "true")); pEnablePasswordRetrieval = Convert.ToBoolean(GetConfigValue(config["enablePasswordRetrieval"], "true")); pRequiresQuestionAndAnswer = Convert.ToBoolean(GetConfigValue(config["requiresQuestionAndAnswer"], "false")); pRequiresUniqueEmail = Convert.ToBoolean(GetConfigValue(config["requiresUniqueEmail"], "true")); string temp_format = config["passwordFormat"]; if (temp_format == null) temp_format = "Hashed"; switch (temp_format) { case "Hashed": pPasswordFormat = MembershipPasswordFormat.Hashed; break; case "Encrypted": pPasswordFormat = MembershipPasswordFormat.Encrypted; break; case "Clear": pPasswordFormat = MembershipPasswordFormat.Clear; break; default: throw new ProviderException("Password format not supported."); } // Get encryption and decryption key information from the configuration. Configuration cfg = WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath); machineKey = (MachineKeySection)cfg.GetSection("system.web/machineKey"); if (machineKey.ValidationKey.Contains("AutoGenerate")) if (PasswordFormat != MembershipPasswordFormat.Clear) throw new ProviderException("Hashed or Encrypted passwords " + "are not supported with auto-generated keys."); }
public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config) { if (config == null) { NullArgumentException("config"); } if (string.IsNullOrEmpty(name)) { name = "MySqlExtendedMembershipProvider"; } if (string.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", string.Format("MySql Default {0} Description", name)); } base.Initialize(name, config); var appName = GetConfigValue(config["applicationName"], HostingEnvironment.SiteName); _maxPwdAttempts = Int32.Parse(GetConfigValue(config["maxInvalidPasswordAttempts"], "5")); _pwdAttemptWindow = Int32.Parse(GetConfigValue(config["passwordAttemptWindow"], "10")); _minReqNonAlphanumericalChars = Int32.Parse(GetConfigValue(config["minRequiredNonalphanumericCharacters"], "1")); _minReqPwdLength = Int32.Parse(GetConfigValue(config["minRequiredPasswordLength"], "7")); _pwdStrenghtRegex = GetConfigValue(config["passwordStrengthRegularExpression"], ""); _enablePwdReset = bool.Parse(GetConfigValue(config["enablePasswordReset"], "True")); _enablePwdRetrival = bool.Parse(GetConfigValue(config["enablePasswordRetrieval"], "False")); _reqQuestionAnswer = bool.Parse(GetConfigValue(config["requiresQuestionAndAnswer"], "False")); _reqUniqueEmail = bool.Parse(GetConfigValue(config["requiresUniqueEmail"], "True")); var pwdFormat = !string.IsNullOrEmpty(config["passwordFormat"]) ? config["passwordFormat"].ToString().ToLowerInvariant() : "hashed"; switch (pwdFormat) { case "hashed": _pwdFormat = MembershipPasswordFormat.Hashed; break; case "encrypted": _pwdFormat = MembershipPasswordFormat.Encrypted; break; case "clear": _pwdFormat = MembershipPasswordFormat.Clear; break; default: throw new ProviderException(Resources.PasswordFormatNotSupported); } if (_pwdFormat == MembershipPasswordFormat.Hashed) { if (_enablePwdRetrival) throw new ProviderException(Resources.CannotRetrieveHashedPasswords); } _app = new Application(appName, base.Description); ConnectionStringSettings connStrSettings = ConfigurationManager.ConnectionStrings[config["connectionStringName"]]; _connString = connStrSettings != null ? connStrSettings.ConnectionString.Trim() : ""; if (string.IsNullOrEmpty(_connString)) return; UserTableName = GetConfigValue(config["userTableName"], ""); UserIdColumn = GetConfigValue(config["userIdColumn"], ""); UserNameColumn = GetConfigValue(config["userNameColumn"], ""); _autoGenerateTables = bool.Parse(GetConfigValue(config["autoGenerateTables"], "True")); if (_autoGenerateTables) CreateTables(); else ValidateUserTable(); Initialized = true; }
public override void Initialize(string name, NameValueCollection config) { if (config == null) { throw new ArgumentNullException("config"); } if (String.IsNullOrEmpty(name)) { name = "DomainMembershipProvider"; } if (string.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", "Membership $safeprojectname$ Provider"); } base.Initialize(name, config); _EnablePasswordRetrieval = GetBooleanValue(config, "enablePasswordRetrieval", false); _EnablePasswordReset = GetBooleanValue(config, "enablePasswordReset", false); _RequiresQuestionAndAnswer = GetBooleanValue(config, "requiresQuestionAndAnswer", false); _RequiresUniqueEmail = GetBooleanValue(config, "requiresUniqueEmail", true); _MaxInvalidPasswordAttempts = GetIntValue(config, "maxInvalidPasswordAttempts", 5, false, 0); _PasswordAttemptWindow = GetIntValue(config, "passwordAttemptWindow", 10, false, 0); _MinRequiredPasswordLength = GetIntValue(config, "minRequiredPasswordLength", 7, false, 64); _MinRequiredNonalphanumericCharacters = GetIntValue(config, "minRequiredNonalphanumericCharacters", 0, true, 16); _HashAlgorithmType = config["hashAlgorithmType"]; if (String.IsNullOrEmpty(_HashAlgorithmType)) { _HashAlgorithmType = "SHA1"; } _PasswordStrengthRegularExpression = config["passwordStrengthRegularExpression"]; if (_PasswordStrengthRegularExpression != null) { _PasswordStrengthRegularExpression = _PasswordStrengthRegularExpression.Trim(); if (_PasswordStrengthRegularExpression.Length != 0) { try { Regex regex = new Regex(_PasswordStrengthRegularExpression); } catch (ArgumentException e) { throw new ProviderException(e.Message, e); } } } else { _PasswordStrengthRegularExpression = string.Empty; } _AppName = config["applicationName"]; if (string.IsNullOrEmpty(_AppName)) { _AppName = GetDefaultAppName(); } if (_AppName.Length > 255) { throw new ProviderException("Provider application name is too long, max length is 255."); } string strTemp = config["passwordFormat"]; if (strTemp == null) { strTemp = "Hashed"; } switch (strTemp) { case "Clear": _PasswordFormat = MembershipPasswordFormat.Clear; break; case "Encrypted": _PasswordFormat = MembershipPasswordFormat.Encrypted; break; case "Hashed": _PasswordFormat = MembershipPasswordFormat.Hashed; break; default: throw new ProviderException("Bad password format"); } if (_PasswordFormat == MembershipPasswordFormat.Hashed && _EnablePasswordRetrieval) { throw new ProviderException("Provider cannot retrieve hashed password"); } /* _DatabaseFileName = config["connectionStringName"]; if (_DatabaseFileName == null || _DatabaseFileName.Length < 1) { throw new ProviderException("Connection name not specified"); } string temp = AccessConnectionHelper.GetFileNameFromConnectionName(_DatabaseFileName, true); if (temp == null || temp.Length < 1) { throw new ProviderException("Connection string not found: " + _DatabaseFileName); } _DatabaseFileName = temp; // Make sure connection is good AccessConnectionHelper.CheckConnectionString(_DatabaseFileName); config.Remove("connectionStringName"); */ config.Remove("enablePasswordRetrieval"); config.Remove("enablePasswordReset"); config.Remove("requiresQuestionAndAnswer"); config.Remove("applicationName"); config.Remove("requiresUniqueEmail"); config.Remove("maxInvalidPasswordAttempts"); config.Remove("passwordAttemptWindow"); config.Remove("passwordFormat"); config.Remove("name"); config.Remove("description"); config.Remove("minRequiredPasswordLength"); config.Remove("minRequiredNonalphanumericCharacters"); config.Remove("passwordStrengthRegularExpression"); config.Remove("hashAlgorithmType"); if (config.Count > 0) { string attribUnrecognized = config.GetKey(0); if (!String.IsNullOrEmpty(attribUnrecognized)) { throw new ProviderException("Provider unrecognized attribute: " + attribUnrecognized); } } }
public override void Initialize(string name, NameValueCollection config) { if (config == null) throw new ArgumentNullException("config"); if (name == null || name.Length == 0) name = "ELMemebershipProvider"; if (String.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", "ELinq Membership provider"); } base.Initialize(name, config); maxInvalidPasswordAttempts = config.Get<int>( "maxInvalidPasswordAttempts",5); passwordAttemptWindow = config.Get<int>("passwordAttemptWindow",10); minRequiredNonAlphanumericCharacters = config.Get<int>("minRequiredNonAlphanumericCharacters",1); minRequiredPasswordLength = config.Get<int>("minRequiredPasswordLength",7); passwordStrengthRegularExpression =config.Get<string>("passwordStrengthRegularExpression", ""); enablePasswordReset =config.Get<bool>("enablePasswordReset",true); enablePasswordRetrieval = config.Get<bool>("enablePasswordRetrieval",true); requiresQuestionAndAnswer = config.Get<bool>("requiresQuestionAndAnswer",false); requiresUniqueEmail =config.Get<bool>("requiresUniqueEmail",true); switch (config.Get<string>("passwordFormat", "Clear")) { case "Hashed": passwordFormat = MembershipPasswordFormat.Hashed; break; case "Encrypted": passwordFormat = MembershipPasswordFormat.Encrypted; break; case "Clear": passwordFormat = MembershipPasswordFormat.Clear; break; default: throw new ProviderException("Password format not supported."); } //Encryption skipped var cfg = WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath); _machineKey = (MachineKeySection)cfg.GetSection("system.web/machineKey"); if (_machineKey.ValidationKey.Contains("AutoGenerate")) if (PasswordFormat != MembershipPasswordFormat.Clear) throw new ProviderException("Hashed or Encrypted passwords are not supported with auto-generated keys."); var connectionStringName = config["connectionStringName"]; UnitOfWork.Configure(connectionStringName); ApplicationName = config["applicationName"]; if (ApplicationName.IsNullOrEmpty()) ApplicationName = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath; else if(ApplicationName != "/") { var site = UnitOfWork.Current.CreateRepository<Site>().FirstOrDefault(p => p.Id == ApplicationName && p.Status == Enums.SiteStatus.Enable); if(site == null) throw new ProviderException("ApplicationName not exists."); } }