Writing a custom membership provider for the login control in ASP. NET 2.0

Source: Internet
Author: User

In ASP. NET 2.0 with Visual Studio (VS) 2005, you can program custom authenticated pages quickly with the membership login controls provided. these controls can be found in VS 2005 in the toolbox under the login section and include: pointer, login, loginview, passwordrecovery, loginstatus, loginname, createuserwizard, and changepassword. these controls can be found in the Framework library as a part ofSystem.Web.SecurityNamespace. This article will focus on the login control.

Note:This article was written based on the November 2004 community release version of Visual Studio 2005. due to the pre-release status of the information in this article, any URLs, class names, control names, etc may change before release.

What this article covers

The login control and the membership provider

Membership providers

Steps involved when using a custom provider with the login Control

How the login control works

Classes you need to provide

Mycustommembershipprovider: membershipprovider

Successful validation with the login Control

Failed validation with the login Control

Web. config

Required config. Web sections

Why use the new ASP. NET 2.0 membership controls at all?

Summary

References

 

The current msdn location for the documentation is:
Http://whidbey.msdn.microsoft.com/library/default.asp? Url =/library/en-US/dv_fxnetstart/html/50c4d770-0bb4-4e6a-bcf0-966bc7a3de77.asp.

System. Web. Security:
Http://whidbey.msdn.microsoft.com/library/default.asp? Url =/library/en-US/cpref/html/n_system_web_security.asp.

System. Web. UI. webcontrols:
Http://whidbey.msdn.microsoft.com/library/default.asp? Url =/library/en-US/cpref/html/t_system_web_ui_webcontrols_login.asp.

The new Login control provided with ASP. NET 2.0 is a simple way to implement validation for your web site. Developing a custom provider to interact with your own membership database is easy.

Since there is some programming work to get the new controls to talk to your old database structure, you may be asking yourself is it worth the trouble? The answer to this seems to be an active debate on several discussion boards.

The benefits of this method are:

  1. You can program the custom provider to provide as little or as much as you need. if you just want the login control to work with your custom membership database, you don't necessarily have to write a lot of code. you will have to be more thoughtful in your upfront design to make sure you are covering just what you need.
  2. The new Web-based membership administration functionality in ASP. NET 2.0 will consume your custom provider. so you get both the ability to use the new controls and the ability to use the new web-based administration features.
  3. Assuming Microsoft will grow this area of functionality overtime, you can continue to make use of your original work.

The disadvantages of this method are:

  1. The new login controls may be more, less, or different than what you need for your web site. most Web sites already have this membership authentication functionality so rewriting just to get it into ASP. NET 2.0 is probably a poor demo.
  2. If you have your own administration Web site or program for your custom membership, writing the additional code to make use of the new web-based membership administration functionality is not necessary -- just don't write those pieces. it's easy to tell which pieces to skip because all the required functions for the Web-based administration deal with collections of users whereas the login control functions deal with a single user.
  3. Microsoft may abandon these controls. It's not likely but it is possible.
  • Authorization: This section specifies who can access that location (directory ).
  • Authentication: This section specifies how the location is accessed. In the above example<authentication>Section is specified for the entire web site and uses~/support/login.aspxFile as the authentication file. This is the file where the login control will be used.
  • Membership: This is the section that ties the login control to the custom membership provider.

Theweb.configFile will need several new pieces. In order to glue the login control to your custom membership provider, you will need a section called<membership>. You can set the properties of the custom provider in this section. You can also control these properties from the custom membership provider class.web.configUsed for this article assumes some aspx files shoshould be accessible only after login is validated, and some files shoshould always be available. the two types of files are located in the 'support 'and 'support _ unrestricted' directories used in<location>Tags.

<?xml version="1.0"?>
<configuration >
  <appSettings>
    <add key="ConnectionString" value="server=XXX;database=XXX;uid=XXX;password=XXX;"/>
  </appSettings>
  <system.web>
    <compilation debug="true"/>
    <authorization>
      <allow users="*" />
    </authorization>
    <authentication mode="Forms">
      <forms name=".ASPXAUTH"
        loginUrl="~/support/Login.aspx"
        protection="Validation"
        timeout="999999"
      />
    </authentication>
    <membership defaultProvider="MyCustomMembershipProvider" userIsOnlineTimeWindow="15">
      <providers>
        <add name="MyCustomMembershipProvider"
          type="PostPointSoftware.MyCustomMembershipProvider"
          enablePasswordRetrieval="true"
          enablePasswordReset="true"
          requiresQuestionAndAnswer="false"
          applicationName="/"
          requiresUniqueEmail="true"
          passwordFormat="Clear"
          description="Stores and retrieves membership data from SQL Server"
          decryptionKey="68d288624f967bce6d93957b5341f931f73d25fef798ba75"
          validationKey="65a31e547b659a6e35fdc029de3acce43f8914cb1b2
                         4fff3e1aef13be438505b3f5becb5702d15bc7b98cd
                         6fd2b7702b46ff63fdc9ea8979f6508c82638b129a"
        />
      </providers>
    </membership>
  </system.web>
  <location path="images">
    <system.web>
      <compilation debug="true"/>
      <authorization>
        <allow users="*" />
      </authorization>
    </system.web>
  </location>
  <location path="support">
    <system.web>
      <compilation debug="true"/>
      <authorization>
        <deny users="?" />
      </authorization>
    </system.web>
  </location>
  <location path="support_unrestricted">
    <system.web>
      <compilation debug="true"/>
      <authorization>
        <allow users="*" />
      </authorization>
    </system.web>
  </location>
</configuration>

The login control has attributes properties, methods, and events to manage the look and feel of the control both on the first instance of the page as well as post back. A default failure message is provided and will appear on the login control if validation is unsuccessful.

Upon successful validation, the login control will redirect to the page referenced inDestinationPageURLProperty, let's call this pagehello.aspx. This valid user is now in a context variable and can be retrieved withContext.User.IdentityProperty.

This class is called from the login Control for validation of the user's email and user's password. this class has several properties and methods that are required to make the glue between the login control and your custom provider due the inheritance fromMembershipProvider. You will see inMyCustomMembershipProviderThat they are provided but throw "not implemented" exceptions.

The two important methods inMyCustomMembershipProviderFor the custom provider areInitialize, AndValidateUser.InitializeIs another place besidesweb.configFile to set properties for your custom provider.ValidateUserIs the main function for the login control to validate the user and password.

public override bool ValidateUser(string strName, string strPassword)
{
    //This is the custom function you need to write. It can do anything you want.
    //The code below is just one example.

    // strName is really an email address in this implementation

    bool boolReturn = false;

    // Here is your custom user object connecting to your custom membership database
    MyUserProvider oUserProvider = new MyUserProvider();
    MyUser oUser = oUserProvider.FindUser(strName);

    if (oUser == null)
        return boolReturn;

    // Here is your custom validation of the user and password
    boolReturn = oUser.ValidateUsersPasswordForLogon(strPassword);

    return boolReturn;
}

ValidateUserTakes two parameters which are the name and password of the user. for other Web sites, the name will be the user's email address. the method returns true or false depending on the results of this validation. all the code inside the method is up to you to provide. the Code provided in this above example is just one possibility.

  • A custom class inheriting fromSystem.Web.Security.MembershipProvider. In this article, it will be calledMyCustomMembershipProvider. This is the custom membership provider.
  • A class or classes that glue the above custom class to your database. In this Article, these will be calledMyCustomUserAndMyCustomUserProvider. These two classes cocould have easily been combined into a single class. this is a choice you can make as you write your own provider implementation. note: If you were implementing the Standard providers in the framework provided for active directory or SQL Server, you wocould use the membershipuser class from the framework for this.

The login control provides two textboxes for a user email and a user password, along with a submit button. once the user provides this information and clicks on the submit button, the custom membership provider class is called to authenticate the user. once the user has been authenticated,Context.User.Identity.IsAuthenticatedProperty is set to true. The login control'sDestinationPageURLProperty tells the Web site where to direct the user if the validation is successful.

The login control is found in the framework as a part ofSystem.Web.UI.WebControlsNamespace as the login class. This class contains the functionality for the login control. The majority of the functionality deals with visual style and event handling.

<asp:Login ID="Login1" runat="server" DestinationPageURL="support.aspx" ></asp:Login>

You don't need to have any code inLogin.aspx.csCode page. The control knows how to call the custom provider which does all the work because the provider is listed inweb.config. If you wanted to change the look and feel of the control on first time to the page or post back, You cocould manipulate the properties, methods, and events in the code behind. but again, that is optional.

For this article,login.aspx.csCode behind page is a shell page provided by Visual Studio with no changes.

There are three main steps required to use a custom provider with the login control.

  • The login control needs to be placed on a ASPX page (login.aspx).
  • The custom provider class needs to inherit fromMembershipProviderAnd override certain methods.
  • Theweb.configFile needs to be modified to use a custom provider.

The login controls ship with at least two Microsoft-supplied providers: Active Directory and SQL Server. both of these providers use a specific data schema. this is great for new web sites, where an authentication schema is not already established, because you can adopt one of these types of authentication and have the majority of the design and programming work done for you. however, if you are working with an existing database structure, you can easily program a custom provider to get these new login controls to talk to your old data structure.

A membership provider is the glue between the login control and the membership database. the login control doesn' t care if the membership provider is a custom provider or a Microsoft provider. the login control knows which provider to instantiate Based on entries inweb.configFile. The custom provider acts just like the Microsoft-supplied providers because it inherits from and overrides the membershipprovider class.

This article focuses on the login control using a custom SQL Server membership database. none of the other controls will be discussed and none of the functions for the Web-based membership administration will be covered. for functionality and breech, this article provides the minimum required to connect the login control with the custom membership provider. you shoshould construct E both the control and the membershipprovider class in the framework to operate e your options.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.