Report CopyRight/DMCA Form For : Microsoft Asp Net Providers
Microsoft ASP NET 2 0 includes a number of services that store state in databases and other storage media For example the session state service manages per user session state by storing it in process in memory in the application domain of the host application in memory in an external process the state server process or in a Microsoft SQL Server database whereas the membership
Introduction, Microsoft ASP NET 2 0 includes a number of services that store state in databases and. other storage media For example the session state service manages per user session. state by storing it in process in memory in the application domain of the host. application in memory in an external process the state server process or in a. Microsoft SQL Server database whereas the membership service stores user names. passwords and other membership data in Microsoft SQL Server or Microsoft Active. These and other state management services in ASP NET 2 0 use the provider model. pictured in Figure 1 to maximize storage flexibility Providers abstract storage media in. much the same way that device drivers abstract hardware devices The membership. service is equally at home using SQL Server or Active Directory because ASP NET 2 0. includes providers for each Moreover ASP NET 2 0 can be extended with custom. providers to add support for Web services Oracle databases SQL Server databases with. custom schemas and other media not supported by the built in providers. Figure 1 The ASP NET 2 0 provider model, Table 1 lists the providers that are included with ASP NET 2 0. Table 1 ASP NET 2 0 providers,Provider Type Built In Provider s. Membership System Web Security ActiveDirectoryMembershipProvider. System Web Security SqlMembershipProvider, Role System Web Security AuthorizationStoreRoleProvider. management System Web Security SqlRoleProvider,System Web Security WindowsTokenRoleProvider. Site map System Web XmlSiteMapProvider,Profile System Web Profile SqlProfileProvider. Session state System Web SessionState InProcSessionStateStore. System Web SessionState OutOfProcSessionStateStore. System Web SessionState SqlSessionStateStore, Web events System Web Management EventLogWebEventProvider. System Web Management SimpleMailWebEventProvider, System Web Management TemplatedMailWebEventProvider. System Web Management SqlWebEventProvider,System Web Management TraceWebEventProvider. System Web Management WmiWebEventProvider, Web Parts System Web UI WebControls WebParts SqlPersonalizationProvider. personalization, Protected System Configuration DPAPIProtectedConfigurationProvider. configuration System Configuration RSAProtectedConfigurationProvider. This whitepaper documents the design and operation of many of the built in providers It. supplements the providers source code and contains helpful insights for developers. writing custom providers of their own,The SQL Provider Database. Many of the Microsoft ASP NET 2 0 providers are SQL providersproviders that persist. state in SQL Server or SQL Server Express databases The SQL providers include. SqlMembershipProvider SqlRoleProvider SqlProfileProvider SqlSessionStateStore. SqlWebEventProvider and SqlPersonalizationProvider Each stores data using a. predefined schema The Aspnet regsql exe tool that comes with ASP NET 2 0 creates a. SQL Server database with a compatible schema That database which is named. aspnetdb by default will hereafter be referred to as the SQL provider database or simply. the provider database, Figure 2 shows the structure of the SQL provider database Some of the tables are. provider specific The aspnet Membership table for example is used exclusively by. SqlMembershipProvider whereas the aspnet Roles and aspnet UsersInRoles tables are. used exclusively by SqlRoleProvider,Figure 2 The SQL provider database. Other tables are not provider specific but instead exist for the benefit of multiple SQL. providers The aspnet Applications table is a great example Many SQL providers. support scoping of data through the ApplicationName property which is initialized from. the applicationName configuration attribute supported by many providers For example. websites that register membership providers with identical applicationName attributes. share membership data whereas websites that register membership providers with. unique applicationNames do not SQL providers that support ApplicationName scoping. do so by storing application IDs associated with the records that they create and by. including those application IDs in queries performed on the SQL provider database. Application IDs stored in aspnet Membership aspnet Paths and other provider specific. tables refer to the aspnet Applications table which contains a list of extant application. IDs and the corresponding application names Table 2 documents the schema of the. aspnet Applications table The provider database contains a stored procedure named. aspnet Applications CreateApplication that providers or stored procedures can call to. retrieve an application ID from the aspnet Applications table or to create a new one if. the specified application doesn t exist,Table 2 The aspnet Applications table. Column Name Column Type Description,ApplicationId uniqueidentifier Application ID. ApplicationName nvarchar 256 Application name, LoweredApplicationName nvarchar 256 Application name lowercase. Description nvarchar 256 Application description, aspnet Users is another example of a table that s shared by SQL providers It stores. core provider agnostic information regarding users including user names and user IDs. SqlMembershipProvider stores membership user data in the aspnet Membership table. but that table contains a UserId column that refers to the column of the same name in. aspnet Users Similarly SqlRoleProvider stores data mapping users to roles in the. aspnet UsersInRoles table and that table contains both a UserId column referring to the. column of the same name in aspnet Users and a RoleId column referring to the column. of the same name in aspnet Roles Table 3 documents the schema of the aspnet Users. Table 3 The aspnet Users table,Column Name Column Type Description. ApplicationId uniqueidentifier Application ID,UserId uniqueidentifier User ID. UserName nvarchar 256 User name,LoweredUserName nvarchar 256 User name lowercase. MobileAlias nvarchar 16 User s mobile alias currently not used. IsAnonymous bit 1 Anonymous user 0 Not an anonymous. LastActivityDate datetime Date and time of last activity by this user. Developers are sometimes surprised to find that the aspnet Users table s. UserName column contains alphanumeric identifiers GUIDs as well as string user. names Records containing GUIDs for user names are created when. SqlProfileProvider or SqlPersonalizationProvider persists data on behalf of. anonymous users, The SQL providers never access tables in the provider database directly Instead they. use stored procedures When SqlMembershipProvider s CreateUser method is called for. example it calls a stored procedure named aspnet Membership CreateUser to add a. new membership user to the provider database aspnet Membership CreateUser adds a. record representing that user to the aspnet Membership table another record. representing that user to the aspnet Users table and if necessary a record denoting a. new application to the aspnet Applications table The use of stored procedures hides the. database schema from the provider which simplifies porting SQL providers to other. database types for example Oracle databases and to SQL Server databases that. utilize custom schemas Stored procedures that perform multistep updates typically use. database transactions to roll back changes if an error occurs before the last step is. completed There are a few cases in which providers manage transactions themselves. in order to support batch deletes,SQL Server Express. Rather than use a pre existing SQL provider database the Microsoft SQL providers are. equally happy to use a database managed by SQL Server Express herafter referred to. as the express database, Internally the express database has the same schema as the SQL provider database. The difference between the databases lies in how they re created The SQL provider. database is created externally when you run Aspnet regsql exe or an equivalent tool. The express database is created automatically the first time it s needed. Each Microsoft SQL provider with the exception of SqlSessionStateStore which doesn t. support express databases has logic built in to automatically create the express. database The logic lives in a helper class named SqlConnectionHelper Rather than. create SqlConnections from raw connection strings Microsoft SQL providers pass. connection strings to SqlConnectionHelper GetConnection as follows. SqlConnectionHolder holder SqlConnectionHelper GetConnection. sqlConnectionString true, SqlConnectionHelper GetConnection parses the connection string and automatically. creates the express database if the connection string meets certain criteria and if the. database doesn t already exist, When a Microsoft SQL provider needs an actual SqlConnection it extracts it from. the Connection property of the SqlConnectionHolder as follows. SqlCommand cmd new SqlCommand dbo aspnet Membership CreateUser. holder Connection, Similarly it closes the connection by calling SqlConnectionHolder Close. The main purpose of the SqlConnectionHolder class is to simplify the security. model when SQL providers are used in a website with client impersonation. enabled SqlConnectionHolder encapsulates logic that temporarily reverts the. thread identity to that of the current process identity or application impersonation. identity when connecting to SQL Server As a result SQL providers run with a. trusted subsystem model that doesn t require individual users to have access. rights to the provider database, The default LocalSqlServer connection string in Machine config is an excellent example. of a connection string that results in automatic creation of the express database. data source SQLEXPRESS Integrated, Security SSPI AttachDBFilename DataDirectory aspnetdb mdf User. Instance true, The presence of User Instance true and AttachDBFilename DataDirectory cause. SqlConnectionHelper to conclude that the connection string targets SQL Server Express. and triggers the database s creation The presence of data source SQLEXPRESS in. the connection string does not factor into the decision because SqlConnectionHelper. supports non default as well as default instances of SQL Server Express The. DataDirectory portion of the connection string specifies that the MDF file is located. inthe App Data directory SqlConnectionHelper derives the database name from the. MDF file name It also creates an App Data folder to hold the MDF if the folder doesn t. already exist, When SqlConnectionHelper creates the express database it sets SIZE to 10 10 MB and. FILEGROWTH to 50 The database s sort order case sensitivity accent sensitivity and. other locale dependent settings are inherited from the default SQL Server Express. instance which ensures that the database locale is consistent with that of the host. The extra overhead incurred by checking for the existence of the express database. before using it means that Microsoft SQL providers run marginally slower against. SQL Server Express than SQL Server Hopefully the small performance loss is. offset by the added convenience of automatically created express databases. Membership Providers, Membership providers provide the interface between Microsoft ASP NET s membership. service and membership data sources ASP NET 2 0 ships with two membership. SqlMembershipProvider which stores membership data in Microsoft SQL Server and. SQL Server Express databases, ActiveDirectoryMembershipProvider which retrieves membership data from Microsoft. Active Directory, The fundamental job of a membership provider is to manage the data regarding a site s. registered users and to provide methods for creating users deleting users verifying. login credentials changing passwords and so on The Microsoft NET Framework s. System Web Security namespace includes a class named MembershipUser that defines. the basic attributes of a membership user and that a membership provider uses to. represent individual users It also includes a base class named MembershipProvider that. defines the basic characteristics of a membership provider MembershipProvider is. prototyped as follows, public abstract class MembershipProvider ProviderBase. Abstract properties,public abstract bool EnablePasswordRetrieval get. public abstract bool EnablePasswordReset get, public abstract bool RequiresQuestionAndAnswer get. public abstract string ApplicationName get set, public abstract int MaxInvalidPasswordAttempts get. public abstract int PasswordAttemptWindow get,public abstract bool RequiresUniqueEmail get. public abstract MembershipPasswordFormat PasswordFormat get. public abstract int MinRequiredPasswordLength get, public abstract int MinRequiredNonAlphanumericCharacters get. public abstract string PasswordStrengthRegularExpression get. Abstract methods, public abstract MembershipUser CreateUser string username. string password string email string passwordQuestion. string passwordAnswer bool isApproved object providerUserKey. out MembershipCreateStatus status, public abstract bool ChangePasswordQuestionAndAnswer. string username string password, string newPasswordQuestion string newPasswordAnswer. public abstract string GetPassword string username. string answer, public abstract bool ChangePassword string username. string oldPassword string newPassword, public abstract string ResetPassword string username. string answer, public abstract void UpdateUser MembershipUser user. public abstract bool ValidateUser string username,string password. public abstract bool UnlockUser string userName, public abstract MembershipUser GetUser object providerUserKey. bool userIsOnline, public abstract MembershipUser GetUser string username. bool userIsOnline, public abstract string GetUserNameByEmail string email. public abstract bool DeleteUser string username,bool deleteAllRelatedData. public abstract MembershipUserCollection GetAllUsers. int pageIndex int pageSize out int totalRecords,public abstract int GetNumberOfUsersOnline. public abstract MembershipUserCollection FindUsersByName. string usernameToMatch int pageIndex int pageSize,out int totalRecords. public abstract MembershipUserCollection FindUsersByEmail. string emailToMatch int pageIndex int pageSize,out int totalRecords. Virtual methods, protected virtual byte EncryptPassword byte password. protected virtual byte DecryptPassword byte encodedPassword. protected virtual void OnValidatingPassword,ValidatePasswordEventArgs e. public event MembershipValidatePasswordEventHandler. ValidatingPassword, The following sections document the implementation of SqlMembershipProvider which. derives from MembershipProvider,SqlMembershipProvider. SqlMembershipProvider is the Microsoft membership provider for SQL Server databases. It stores membership data using the schema documented in Data Schema and it uses. the stored procedures documented in Data Access All knowledge of the database. schema is hidden in the stored procedures so porting SqlMembershipProvider to other. database types requires little more than modifying the stored procedures Depending. on the targeted database type the ADO NET code used to call the stored procedures. might have to change too The Microsoft Oracle NET provider for example uses a. different syntax for named parameters, The ultimate reference for SqlMembershipProvider is the SqlMembershipProvider source. code which is found in SqlMembershipProvider cs The sections that follow highlight key. aspects of SqlMembershipProvider s design and operation. Provider Initialization, Initialization occurs in SqlMembershipProvider Initialize which is called one timewhen. the provider is loadedby ASP NET SqlMembershipProvider Initialize s duties include. Initializing the various SqlMembershipProvider properties such as. EnablePasswordRetrieval and EnablePasswordReset from the corresponding. configuration attributes enablePasswordRetrieval enablePasswordReset and so on. Performing common sense checks on the property valuesfor example throwing an. exception if PasswordFormat is hashed MembershipPasswordFormat Hashed but. EnablePasswordRetrieval is true By definition passwords can t be computed from. password hashes, Throwing an exception if unrecognized configuration attributes remain after all. supported configuration attributes are processed, SqlMembershipProvider Initialize also reads the connection string identified by the. connectionStringName attribute from the connectionStrings configuration section. and caches it in a private field It throws a ProviderException if the attribute is empty or. nonexistent or if the attribute references a nonexistent connection string. Data Schema, SqlMembershipProvider stores membership data in the aspnet Membership table of the. provider database Each record in aspnet Membership corresponds to one membership. user Table 4 documents the aspnet Membership table s schema. Table 4 The aspnet Membership table,Column Name Column Type Description. ApplicationId uniqueidentifier Application ID,UserId uniqueidentifier User ID. Password nvarchar 128 Password plaintext hashed or. encrypted base 64 encoded if,hashed or encrypted,PasswordFormat int Password format 0 Plaintext. 1 Hashed 2 Encrypted, PasswordSalt nvarchar 128 Randomly generated 128 bit. value used to salt password,hashes stored in base 64. encoded form, MobilePIN nvarchar 16 User s mobile PIN currently not. Email nvarchar 256 User s e mail address,LoweredEmail nvarchar 256 User s e mail address. PasswordQuestion nvarchar 256 Password question, PasswordAnswer nvarchar 128 Answer to password question. IsApproved bit 1 Approved 0 Not approved,IsLockedOut bit 1 Locked out 0 Not locked out. CreateDate datetime Date and time this account was. LastLoginDate datetime Date and time of this user s last. LastPasswordChangedDate datetime Date and time this user s. password was last changed, LastLockoutDate datetime Date and time this user was last. locked out, FailedPasswordAttemptCount int Number of consecutive failed. login attempts, FailedPasswordAttempt datetime Date and time of first failed login. WindowStart if FailedPasswordAttemptCount is, FailedPasswordAnswer int Number of consecutive failed. AttemptCount password answer attempts, FailedPasswordAnswer datetime Date and time of first failed. AttemptWindowStart password answer if,FailedPasswordAnswerAttemptCo. unt is nonzero,Comment ntext Additional text, The aspnet Membership table has foreign key relationships with two other provider. database tables aspnet Applications see Table 2 and aspnet Users see Table 3 The. aspnet Membership table s ApplicationId column references the column of the same. name in the aspnet Applications table Although this column is not strictly necessary. because the UserId can be used to derive the ApplicationId the ApplicationId column. was added to the aspnet Membership table to speed up queries and reduce the need to. join through to the aspnet Users table aspnet Membership s UserId column references. the column of the same name in the aspnet Users table A complete record for a given. membership user consists of data corresponding to that user s user ID in the. aspnet Users table and data corresponding to the same user ID in the. aspnet Membership table Stored procedures such as, aspnet Membership GetUserByName pull data from both tables to create. MembershipUser objects representing individual users. Scoping of Membership Data, Websites that register membership providers with identical applicationName attributes. share membership data whereas websites that register membership providers with. unique applicationNames do not To that end SqlMembershipProvider records an. application ID in the ApplicationId field of each record in the aspnet Membership table. aspnet Membership s ApplicationId field refers to the field of the same name in the. aspnet Applications table and each unique applicationName has a corresponding. ApplicationId in that table,Data Access, SqlMembershipProvider performs all database accesses through stored procedures. Table 5 lists the stored procedures that it uses, Table 5 Stored procedures used by SqlMembershipProvider. Stored Procedure Description, aspnet Membership ChangePassword Changes the specified user s. QuestionAndAnswer password question and answer, aspnet Membership CreateUser Adds a new membership user to. the membership database,Records the user in the,aspnet Users and. aspnet Membership tables and if,necessary adds a new application. to the aspnet Applications table, aspnet Membership FindUsersByEmail Retrieves records from. aspnet Membership table with e,mail addresses matching the. specified pattern and with the,specified application ID. aspnet Membership FindUsersByName Retrieves records from. aspnet Membership table with,user names matching the specified. pattern and with the specified,application ID, aspnet Membership GetAllUsers Retrieves all users from the. aspnet Membership table with the,specified application ID. aspnet Membership GetNumberOfUsersOnline Gets the number of users currently. online those whose last activity, aspnet Membership GetPassword Gets the specified user s password. data from the database Used for,retrieving passwords with a user. supplied password answer, aspnet Membership GetPasswordWithFormat Gets the specified user s password. from the database Used by the,provider to retrieve passwords for. performing password comparisons,for example when ValidateUser. needs to validate a password, aspnet Membership GetUserByEmail Given an e mail address and. application ID retrieves the,corresponding record from the. aspnet Membership table, aspnet Membership GetUserByName Given a user name and application. ID retrieves the corresponding,record from the,aspnet Membership table. aspnet Membership GetUserByUserId Given a user ID and application ID. retrieves the corresponding record,from the aspnet Membership. aspnet Membership ResetPassword Resets the specified user s. password based on a password, aspnet Membership SetPassword Sets the specified user s password. to the password input to the,stored procedure, aspnet Membership UnlockUser Restores login privileges for the. specified user by setting the user s,IsLockedOut bit to 0. aspnet Membership UpdateUser Updates the user s last activity. date in the aspnet Users table and,e mail address comment is. approved status and last login,date in the aspnet Membership. aspnet Membership UpdateUserInfo Updates account locking data for. the specified user in the,aspnet Users and,aspnet Membership tables Used. in conjunction with provider,methods that track bad password. and bad password answer, aspnet Users CreateUser Adds a user to the aspnet Users. table Called by,aspnet Membership CreateUser,aspnet Users DeleteUser Deletes a user from the. aspnet Membership table and,optionally from other SQL provider. tables including aspnet Users, Stored procedure names are generally indicative of the SqlMembershipProvider methods. that call them For example applications call the membership service s. Membership CreateUser method to register new users Membership CreateUser in turn. delegates to the CreateUser method of the default membership provider which in the. case of SqlMembershipProvider validates the input parameters and calls. aspnet Membership CreateUser to register a new user. Creating Membership Users, SqlMembershipProvider CreateUser calls the stored procedure. aspnet Membership CreateUser to create new membership users Before calling the. stored procedure SqlMembershipProvider CreateUser validates the input parameters. encodes the password and if present the password answer provided to it and fires an. OnValidatingPassword event Then aspnet Membership CreateUser performs the. following tasks, 1 Calls the stored procedure aspnet Applications CreateApplication to convert the. application name passed to it which comes from the provider s ApplicationName. property into an application ID If the application name already appears in the. aspnet Applications table aspnet Applications CreateApplication returns the. existing application ID If the application name is not already present in the. aspnet Applications table aspnet Applications CreateApplication adds a new. application to aspnet Applications and returns the application ID. 2 Calls aspnet Users CreateUser to insert a record representing the new user into the. aspnet Users table, 3 Performs an optional check to ensure that the new user s e mail address is unique. with respect to other registered e mail addresses, 4 Updates the LastActivityDate field in the aspnet Users table with the current time. 5 Inserts a record representing the new user into the aspnet Membership table. aspnet Membership CreateUser performs all these steps within a transaction to ensure. that changes are committed as a group or not at all. Deleting Membership Users, Applications call the membership service s Membership DeleteUser method to delete. membership users Membership DeleteUser calls the default membership provider s. DeleteUser method which takes a user name as input and also accepts a bool named. deleteAllRelatedData that specifies whether other data associated with the specified user. should be deleted in addition to membership data Other data includes role data. profile data including anonymous profile datamore on this later and Web Parts. personalization data, SqlMembershipProvider DeleteUser calls the stored procedure aspnet Users DeleteUser. to delete membership users In addition to accepting a user name. aspnet Users DeleteUser accepts a bit mask named TablesToDeleteFrom that. specifies which provider database tables the user should be deleted from If. deleteAllRelatedData is false SqlMembershipProvider DeleteUser passes a bit mask of 1. prompting aspnet Users DeleteUser to delete the user only from the. aspnet Membership table However if deleteAllRelatedData is true. SqlMembershipProvider DeleteUser passes a bit mask of 15 binary 1111 prompting. aspnet Users DeleteUser to delete the specified user from the aspnet Membership. aspnet UsersInRoles aspnet Profile aspnet PersonalizationPerUser and aspnet Users. tables aspnet Users DeleteUser uses a database transaction to ensure that the. deletions are performed in whole or not at all, Another little known fact is that Membership DeleteUser can be used to clean up the. records that accrue in the aspnet Users and aspnet Profile tables when using the. anonymous identification feature to store profile data on behalf of anonymous users. Simply call Membership DeleteUser with deleteAllRelatedData set to true and username. set to Request AnonymousID This deletes the anonymous user s data from the. aspnet Profile table and it deletes the base user record from aspnet Users. Validating Membership Users, Applications call the membership service s Membership ValidateUser method to validate. membership usersthat is to verify that a given user name and password corresponds to. a registered membership user Membership ValidateUser calls the default membership. provider s ValidateUser method which returns true or false indicating whether the user. name and password are valid, SqlMembershipProvider ValidateUser performs the following tasks.