📄 sqlmembershipprovider.cs
字号:
//------------------------------------------------------------------------------
// <copyright file="SqlMembershipProvider.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace Microsoft.Samples {
using System;
using System.Web.Security;
using System.Web;
using System.Web.Configuration;
using System.Security.Principal;
using System.Security.Permissions;
using System.Globalization;
using System.Runtime.Serialization;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Configuration.Provider;
using System.Configuration;
using System.Web.DataAccess;
using System.Web.Management;
using System.Web.Util;
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
// Remove CAS from sample: [AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal)]
// Remove CAS from sample: [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level=AspNetHostingPermissionLevel.Minimal)]
public class SqlMembershipProvider : MembershipProvider
{
////////////////////////////////////////////////////////////
// Public properties
public override bool EnablePasswordRetrieval { get { return _EnablePasswordRetrieval; } }
public override bool EnablePasswordReset { get { return _EnablePasswordReset; } }
public override bool RequiresQuestionAndAnswer { get { return _RequiresQuestionAndAnswer; } }
public override bool RequiresUniqueEmail { get { return _RequiresUniqueEmail; } }
public override MembershipPasswordFormat PasswordFormat { get { return _PasswordFormat; }}
public override int MaxInvalidPasswordAttempts { get { return _MaxInvalidPasswordAttempts; } }
public override int PasswordAttemptWindow { get { return _PasswordAttemptWindow; } }
public override int MinRequiredPasswordLength
{
get { return _MinRequiredPasswordLength; }
}
public override int MinRequiredNonAlphanumericCharacters
{
get { return _MinRequiredNonalphanumericCharacters; }
}
public override string PasswordStrengthRegularExpression
{
get { return _PasswordStrengthRegularExpression; }
}
public override string ApplicationName
{
get { return _AppName; }
set
{
if (String.IsNullOrEmpty(value))
throw new ArgumentNullException("value");
if (value.Length > 256)
throw new ProviderException( SR.GetString( SR.Provider_application_name_too_long ) );
_AppName = value;
}
}
private string _sqlConnectionString;
private bool _EnablePasswordRetrieval;
private bool _EnablePasswordReset;
private bool _RequiresQuestionAndAnswer;
private string _AppName;
private bool _RequiresUniqueEmail;
private int _MaxInvalidPasswordAttempts;
private int _CommandTimeout;
private int _PasswordAttemptWindow;
private int _MinRequiredPasswordLength;
private int _MinRequiredNonalphanumericCharacters;
private string _PasswordStrengthRegularExpression;
private int _SchemaVersionCheck;
private MembershipPasswordFormat _PasswordFormat;
private const int PASSWORD_SIZE = 14;
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
public override void Initialize(string name, NameValueCollection config)
{
// Remove CAS from sample: 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 );
_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));
string temp = config["connectionStringName"];
if (temp == null || temp.Length < 1)
throw new ProviderException(SR.GetString(SR.Connection_name_not_specified));
_sqlConnectionString = SqlConnectionHelper.GetConnectionString(temp, true, true);
if (_sqlConnectionString == null || _sqlConnectionString.Length < 1) {
throw new ProviderException(SR.GetString(SR.Connection_string_not_found, temp));
}
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("commandTimeout");
config.Remove("passwordFormat");
config.Remove("name");
config.Remove("minRequiredPasswordLength");
config.Remove("minRequiredNonalphanumericCharacters");
config.Remove("passwordStrengthRegularExpression");
if (config.Count > 0) {
string attribUnrecognized = config.GetKey(0);
if (!String.IsNullOrEmpty(attribUnrecognized))
throw new ProviderException(SR.GetString(SR.Provider_unrecognized_attribute, attribUnrecognized));
}
}
private void CheckSchemaVersion( SqlConnection connection )
{
string[] features = { "Common", "Membership" };
string version = "1";
SecUtility.CheckSchemaVersion( this,
connection,
features,
version,
ref _SchemaVersionCheck );
}
private int CommandTimeout
{
get{ return _CommandTimeout; }
}
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
public override MembershipUser CreateUser( string username,
string password,
string email,
string passwordQuestion,
string passwordAnswer,
bool isApproved,
object providerUserKey,
out MembershipCreateStatus status )
{
if( !SecUtility.ValidateParameter(ref password, true, true, false, 128))
{
status = MembershipCreateStatus.InvalidPassword;
return null;
}
string salt = GenerateSalt();
string pass = EncodePassword(password, (int)_PasswordFormat, salt);
if ( pass.Length > 128 )
{
status = MembershipCreateStatus.InvalidPassword;
return null;
}
string encodedPasswordAnswer;
if( passwordAnswer != null )
{
passwordAnswer = passwordAnswer.Trim();
}
if (!string.IsNullOrEmpty(passwordAnswer)) {
if( passwordAnswer.Length > 128 )
{
status = MembershipCreateStatus.InvalidAnswer;
return null;
}
encodedPasswordAnswer = EncodePassword(passwordAnswer.ToLower(CultureInfo.InvariantCulture), (int)_PasswordFormat, salt);
}
else
encodedPasswordAnswer = passwordAnswer;
if (!SecUtility.ValidateParameter(ref encodedPasswordAnswer, RequiresQuestionAndAnswer, true, false, 128))
{
status = MembershipCreateStatus.InvalidAnswer;
return null;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -