Document directory
- Verification and authorization
- Provider
- MembershipProvider
- Use Membership Provider
Address: http://www.odetocode.com/Articles/427.aspx
Translation: Ji Jun, European Union software technology company
Over the years, we have written a lot of code to implement form browsing permission management for Internet applications. We code to verify the user name and password, code to hash the password, verify and code to create and manage the user. If you compare two such implementations, you may find that the program structure is similar to the code. Since ASP.net 2.0, website developers no longer need to write such repetitive code to store and verify information. Instead, ASP.net 2.0 provides the Membership Provider and Role Provider to manage the Role and permissions of applications as security and science extensions.
Verification and authorization
Here, Membership Provider and Role Provider provide verification and authorization services for our applications. Authentication is the process of identifying a user. Membership Provider can create a new user name and code in the database, and verify the user'sIdentity. There is also a Membership Provider for the Active Directory, but this article will focus on SQL Server Membership Provider.
ASP.net 2.0 provides a login control that can be dragged to a webpage without coding. These controls directly talk to the Membership Provider. ASP.net 2.0 also provides controls to maintain dynamic user information, including modifying and resetting passwords. All these controls are built on the Membership Provider feature.
Once we know that the user isWho., We can understand that we allow usersWhat-Authorization. ASP.net 2.0's Role Provider allows us to create roles and map multiple users to the corresponding roles. For example, you may set two roles for the Application: Administrator and registered user. A user name is provided. Role Provider can tell us which Role the user belongs. The regionalization or special operations of website applications can be restricted to precise roles.
Of course, your application may have special needs. Maybe your database is not Microsoft SQL Server. Fortunately, Microsoft uses an extensible support model to implement Membership Provider and Role Provider. This support model is the key point of the Membership Provider and Role Provider services, so we should first explain how providers work to expand our article.
Provider
The Provider Model of ASP.net 2.0 provides developers with an extensible method to add their own implementations as a feature to the runtime. Both Membership Provider and Role Provider follow the Provider Model by refining an interface or protocol in ASP.net 2.0. If you create your component to implement the protocol defined by the Provider model, you can insert your code to the ASP.net runtime and replace or extend the existing Provider. The Provider Model in ASP.net 2.0 includes a Provider configuration and initialization infrastructure.
The Provider Model starts with the abstract class ProviderBase. ProviderBase forces the Protocol to require public names and description attributes for all providers, just like a public initialization method. MembershipProvider and RoleProvider are abstract classes inherited from ProviderBase. These classes add additional attributes and methods to define interfaces for their special functions.
For example, MembershipProvider needs a membership class to implement a ValidateUser method. The default Membership Provider in 2.0, SqlMembershipProvider, implements this method by executing a stored procedure in an SQL Server database. If you want to write your own Provider to store the membership information using the XML file, you will have to write the ValidateUser code to verify your password by storing the information in the XML file.
The beauty of the Provider model is that high-level application services can be created on the Provider without the need to know the details after the interface. A good example is the Membership Provider control of ASP.net 2.0, including the Login control, CreateUser control, and LoginStatus control. All these controls follow the MembershipProvider protocol. In some cases, the Login control must call the ValidateUser method in the configured Provider. The Login control does not care whether there is access to the SQL Server database or XML files. All Login controls focus on whether the returned values are true or false by using the user name and password.
MembershipProvider
The role of MembershipProvider is to provide an indirect layer between the Membership Provider control, just like the data storage of LoginControl and member qualification information. Indirectly, we can use any data storage (SQL Server, Oracle, XML, Web Service, Active Directory ), as long as we have a Provider that hides details after the public interfaces and attributes of the object class. As we mentioned earlier, ASP.net 2.0 includes the Provider of SQL Server and Active Directory.
After. NET is successfully installed, the SqlMembershipProvider class is set to the default Membership Provider in System. Web. You can find the default configuration in machine. config. The configuration of this file is valid for all applications managed by the current computer. The machine. config file can be found in the configuration path installed by. net framework, typically \ Windows \ Microsoft. NET \ Framework \ v2.0.xxxx.
<Membership>
<Providers>
<Add
Name = "AspNetSqlMembershipProvider"
Type = "System. Web. Security. SqlMembershipProvider ,..."
ConnectionStringName = "LocalSqlServer"
EnablePasswordRetrieval = "false"
EnablePasswordReset = "true"
RequiresQuestionAndAnswer = "true"
ApplicationName = "/"
RequiresUniqueEmail = "false"
PasswordFormat = "Hashed"
MaxInvalidPasswordAttempts = "5"
MinRequiredPasswordLength = "7"
MinRequiredNonalphanumericCharacters = "1"
PasswordAttemptWindow = "10"
PasswordStrengthRegularExpression = ""
/>
</Providers>
</Membership>
Configure Membership Provider
Machine. config has many configuration options related to Membership Provider. We can use them-they need to include user password management.
To use the Membership Provider feature, you must use the Login website control in ASP.net 2.0. The CreateUser control provides all interfaces and implementations for getting user names, passwords, emails, security questions, and answers. The PasswordRecovery control allows you to obtain or reset the password by email. For more information about the Login control, see Securing Your Application "ASP. NET tutorials.
The passwordFormat attribute details how providers Store passwords and affects the role of many other Membership providers. SqlMembershipProvider supports three formats: Hashed (the default format is also the safest), Encrypted, and Clear. Use a hash function to encrypt unformatted user passwords and random values by using an irreversible hash algorithm before storing passwords. This method cannot obtain the original password before hashing. To verify the password, the Provider has to compare the entered password and the Stored Password after hash. The Provider can also store the encrypted password (this method can be decrypted and obtain the original value), or store the unhandled password (this method is not recommended ).
The enablePasswordRetrieval option determines whether the Provider can return the user's password through the GetPassword method. If the password format is set to Hashed. The password cannot be obtained again. If the Provider stores encrypted or unprocessed text format, you can email the User Password they forgot, but you need to consider security. When the password is forgotten, a safer option is to reset the user's password to a new value and email it to the user (use requiresUniqueEmail to confirm that the user entered the correct email address ).
EnablePasswordReset option controls the ResetPassword API. ResetPassword: you can set a new and automatically assigned password for the user. The PasswordRecovery control automatically sends a new password to the user. Set the requiresQuestionAndAnswer option to true to prevent malicious users from resetting others' passwords. If this parameter is set to true, the user must provide the answer to the security question before resetting the password. The question and answer text must be provided when the CreateUser control adds a new user.
The Provider allows many attributes to control the password strength. MinRequiredPasswordLength and minRequiredNonalphanumericCharacters Prevent Users From using simple passwords like "abc. If you have special requirements, you can use the passwordStrengthRegularExpression attribute to force the password to pass a regular expression test. Note: The password generated by ResetPassword always meets the password length and non-numeric string quantity requirements, but may not be tested using regular expressions.
SqlMembershipProvider provides many features not mentioned above. For example, the cooperation between maxInvalidPasswordAttempts and passwordAttemptWindow can be used to prevent malicious users from cracking users' accounts. If an incorrect account is entered multiple times, the account will be locked until the UnlockUser method is used to unlock the account.
SQL Server Membership Provider
Other attributes in the Membership Provider section control how SqlMemeberShipProvider interacts with SQL Server. By default, Membership Provider and Role Provider are configured in the machine. config file, and the SQL Server Express database file in the App_data PATH works together. In the configuration above, we can see that the connectionStringName attribute is "LocalSqlServer ". If you find the machine. config connection string segment, you will find the following information:
<Add name = "LocalSqlServer"
ConnectionString = "data source =. \ SQLEXPRESS; Integrated Security = SSPI; AttachDBFilename = | DataDirectory | aspnetdb. mdf; User Instance = true"
ProviderName = "System. Data. SqlClient"/>
You can overwrite the default settings and set all providers to use LocalSqlServer or remote databases or local unstructured databases. The first step is to use ASP.net SQL Server Registration Tool(aspnet_regsql.exe) to create a new database. You can find this tool in the. net framework installation path (WINDOWS \ Microsoft. NET \ Framework \ 2.0.xxxx. If you do not use the command line parameters to directly start the tool, the program will start a wizard to create a new database. The default database name is aspnetdb.
When you have configured the database used by the Provider, you can modify the web. config file or your application to redefine the LocalSqlServer connection string to point to the new database.
<ConnectionStrings>
<Remove name = "LocalSqlServer"/>
<Add name = "LocalSqlServer"
ConnectionString = "server =.; database = aspnetdb; integrated security = sspi;"/>
</ConnectionStrings>
Alternatively, you can define a new connection string and modify the connectionStringName attribute to enable the Provider to use the new connection string.
You can use the ASP.net Configuration tool (Visual Studio under the site menu) to test your settings. Select a different Provider for each feature in the provider column. The following page allows you to test the connection attribute of the Provider. The management tools page also provides functions such as security and user creation.
Another important attribute of Membership Provider configuration is applicationName. ApplicationName allows a database to support multiple website applications. If there are two website applications that want them to share the same user database, give them the same applicationName attribute and point to the same aspnetdb database. If you want them to use the same database but different users, give them each unique applicationName attribute.
Use Membership Provider
To directly interact with the Membership API, use the Membership class in System. Web. Security. The Membership class only includes static members and attributes. However, these static members reflect attributes and methods in the MembershipProvider, and the component calls the configured Provider when appropriate. The following is an example of using encoding to Implement User attributes.
String username = "SwedishChef ";
String password = "bj # kbj1k ";
String email = @ "swede@mailinator.com ";
String question = "The greatest band ever? ";
String answer = "ABBA ";
Bool isApproved = true;
MembershipCreateStatus status;
Membership. CreateUser (
Username, password, email,
Question, answer, isApproved,
Out status );
If (status = MembershipCreateStatus. Success)
{
// Party!
}
An early Membership Provider interface used the ASP.net 2.0 Login controls: Login, LoginView, PasswordRecovery, LoginStatus, LoginName, CreateUserWizard, and ChangePassword. For example, when users enter their usernames and passwords and click the Login button, the ValidateUser method of the current Membership Provider is used. If the built-in control provides all the functions you need, you do not need to write any code. All controls can be set to various styles through styles and templates. You can find these controls under the "Login" category of the Visual Studio toolbar.