Export (0) Print
Expand All

How to: Implement a Custom Membership User

Provides an example that illustrates how to extend the MembershipUser class with a custom membership provider.

While the user System.Web.Profile provides a convenient mechanism for storing information per user in a Web application, the design of your application might require that additional user information be stored with the user authentication information in the Membership data store. In this case, you would need to build a custom membership provider to store and retrieve the user authentication information and the additional user values in your data store (for an example of a custom membership provider, see Implementing a Membership Provider). Additionally, you can extend the MembershipUser class to make the added user values available to application code.

Creating a custom membership user involves the following tasks:

  • Create a class that inherits the MembershipUser class.

  • Create a data source to store authentication information and additional user settings.

  • Create a custom membership provider for the data store. The custom membership provider will contain additional code that can receive objects of the custom membership user type as input, as well as return objects of the custom membership user type.

The examples in this topic show how you can modify the custom membership provider example in How to: Sample Membership Provider Implementation to support a custom membership user implementation.

Create a Custom Membership User

You can create a custom membership user by creating a class that inherits the MembershipUser class, and then including properties that expose the additional user values. Optionally, you can add methods and events to the MembershipUser class as well.

When the Membership class is called to create an instance of your custom MembershipUser, only the constructors defined by the MembershipUser class will be called. If your MembershipUser implementation includes additional constructor overloads, those constructors will only be called by application code that is written specifically to call a custom constructor.

The following code example shows a simple custom membership user that inherits the MembershipUser class and provides two additional properties: IsSubscriber, which is a Boolean property that identifies whether the user subscribes to a service or newsletter for a Web application; and CustomerID, which contains a unique identifier for a separate customer database.

Imports System
Imports System.Web.Security


Namespace Samples.AspNet.Membership.VB

    Public Class OdbcMembershipUser
        Inherits MembershipUser

        Private _IsSubscriber As Boolean
        Private _CustomerID As String

        Public Property IsSubscriber() As Boolean
            Get
                Return _IsSubscriber
            End Get
            Set(ByVal value As Boolean)
                _IsSubscriber = value
            End Set
        End Property

        Public Property CustomerID() As String
            Get
                Return _CustomerID
            End Get
            Set(ByVal value As String)
                _CustomerID = value
            End Set
        End Property

        Public Sub New(ByVal providername As String, _
                       ByVal username As String, _
                       ByVal providerUserKey As Object, _
                       ByVal email As String, _
                       ByVal passwordQuestion As String, _
                       ByVal comment As String, _
                       ByVal isApproved As Boolean, _
                       ByVal isLockedOut As Boolean, _
                       ByVal creationDate As DateTime, _
                       ByVal lastLoginDate As DateTime, _
                       ByVal lastActivityDate As DateTime, _
                       ByVal lastPasswordChangedDate As DateTime, _
                       ByVal lastLockedOutDate As DateTime, _
                       ByVal isSubscriber As Boolean, _
                       ByVal customerID As String)

            MyBase.New(providername, _
                       username, _
                       providerUserKey, _
                       email, _
                       passwordQuestion, _
                       comment, _
                       isApproved, _
                       isLockedOut, _
                       creationDate, _
                       lastLoginDate, _
                       lastActivityDate, _
                       lastPasswordChangedDate, _
                       lastLockedOutDate)

            Me.IsSubscriber = isSubscriber
            Me.CustomerID = customerID

        End Sub

    End Class
End Namespace

For an example of modifying the CreateUserWizard control to include additional user information for a membership user, see How to: Customize the ASP.NET CreateUserWizard Control.

Create a Data Store for the Membership User Data

You will need to provide a data store for the user authentication information for the membership feature, as well as the additional user information for your custom membership user.

The following code example shows a query that you can run in a Microsoft Access database to create a table to store authentication information and property values for your custom membership user.

CREATE TABLE Users
(
  PKID Guid NOT NULL PRIMARY KEY,
  Username Text (255) NOT NULL,
  ApplicationName Text (255) NOT NULL,
  Email Text (128) NOT NULL,
  Comment Text (255),
  Password Text (128) NOT NULL,
  PasswordQuestion Text (255),
  PasswordAnswer Text (255),
  IsApproved YesNo, 
  LastActivityDate DateTime,
  LastLoginDate DateTime,
  LastPasswordChangedDate DateTime,
  CreationDate DateTime, 
  IsOnLine YesNo,
  IsLockedOut YesNo,
  LastLockedOutDate DateTime,
  FailedPasswordAttemptCount Integer,
  FailedPasswordAttemptWindowStart DateTime,
  FailedPasswordAnswerAttemptCount Integer,
  FailedPasswordAnswerAttemptWindowStart DateTime,
  IsSubscriber YesNo,
  CustomerID Text (64)
)

Create a Custom Membership Provider

You will need to create a custom membership provider that supports both your custom membership user type, and your custom membership data store. The GetUser and CreateUser methods of the custom membership provider can be written to return objects of the custom membership user type. The UpdateUser method of the custom membership provider can be written to receive an object of the custom membership user type as input.

The following sections provide guidance on creating a custom membership provider that uses a custom membership user type. The examples build on the code provided in How to: Sample Membership Provider Implementation and use the database schema from the Create a Data Source for the Membership User Data section earlier in this topic.

Modify the GetUser Methods

When working with a custom membership user type, the System.Web.Security.MembershipProvider.GetUser(System.String,System.Boolean) and System.Web.Security.MembershipProvider.GetUser(System.Object,System.Boolean) methods of your membership provider must still return an object of type MembershipUser. Provided your custom membership user class inherits the MembershipUser class, return an object of your custom membership user type as the return value for your implementation of the GetUser methods. Application code can then cast the returned MembershipUser as your custom membership user type to access the additional members of your custom membership user as shown in the following code example.

The following code example shows the modified GetUser methods (and their supporting private method) of the sample membership provider from How to: Sample Membership Provider Implementation, which have been updated to return the custom membership user type from the Create a Custom Membership User section earlier in this topic.

'
' MembershipProvider.GetUser(String, Boolean)
'

Public Overrides Function GetUser(ByVal username As String, _
                                  ByVal userIsOnline As Boolean) As MembershipUser

    Dim conn As OdbcConnection = New OdbcConnection(connectionString)
    Dim cmd As OdbcCommand = New OdbcCommand("SELECT PKID, Username, Email, PasswordQuestion," & _
          " Comment, IsApproved, IsLockedOut, CreationDate, LastLoginDate," & _
          " LastActivityDate, LastPasswordChangedDate, LastLockedOutDate" & _
          " FROM Users  WHERE Username = ? AND ApplicationName = ?", conn)

    cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username
    cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName

    Dim u As OdbcMembershipUser = Nothing
    Dim reader As OdbcDataReader = Nothing

    Try
        conn.Open()

        reader = cmd.ExecuteReader()

        If reader.HasRows Then
            reader.Read()
            u = GetUserFromReader(reader)

            If userIsOnline Then
                Dim updateCmd As OdbcCommand = New OdbcCommand("UPDATE Users  " & _
                          "SET LastActivityDate = ? " & _
                          "WHERE Username = ? AND Applicationname = ?", conn)

                updateCmd.Parameters.Add("@LastActivityDate", OdbcType.DateTime).Value = DateTime.Now
                updateCmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username
                updateCmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName

                updateCmd.ExecuteNonQuery()
            End If
        End If
    Catch e As OdbcException
        If WriteExceptionsToEventLog Then
            WriteToEventLog(e, "GetUser(String, Boolean)")

            Throw New ProviderException(exceptionMessage)
        Else
            Throw e
        End If
    Finally
        If Not reader Is Nothing Then reader.Close()

        conn.Close()
    End Try

    Return u
End Function


'
' MembershipProvider.GetUser(Object, Boolean)
'

Public Overrides Function GetUser(ByVal providerUserKey As Object, _
ByVal userIsOnline As Boolean) As MembershipUser

    Dim conn As OdbcConnection = New OdbcConnection(connectionString)
    Dim cmd As OdbcCommand = New OdbcCommand("SELECT PKID, Username, Email, PasswordQuestion," & _
          " Comment, IsApproved, IsLockedOut, CreationDate, LastLoginDate," & _
          " LastActivityDate, LastPasswordChangedDate, LastLockedOutDate" & _
          " FROM Users  WHERE PKID = ?", conn)

    cmd.Parameters.Add("@PKID", OdbcType.UniqueIdentifier).Value = providerUserKey

    Dim u As OdbcMembershipUser = Nothing
    Dim reader As OdbcDataReader = Nothing

    Try
        conn.Open()

        reader = cmd.ExecuteReader()

        If reader.HasRows Then
            reader.Read()
            u = GetUserFromReader(reader)

            If userIsOnline Then
                Dim updateCmd As OdbcCommand = New OdbcCommand("UPDATE Users  " & _
                          "SET LastActivityDate = ? " & _
                          "WHERE PKID = ?", conn)

                updateCmd.Parameters.Add("@LastActivityDate", OdbcType.DateTime).Value = DateTime.Now
                updateCmd.Parameters.Add("@PKID", OdbcType.UniqueIdentifier).Value = providerUserKey

                updateCmd.ExecuteNonQuery()
            End If
        End If
    Catch e As OdbcException
        If WriteExceptionsToEventLog Then
            WriteToEventLog(e, "GetUser(Object, Boolean)")

            Throw New ProviderException(exceptionMessage)
        Else
            Throw e
        End If
    Finally
        If Not reader Is Nothing Then reader.Close()

        conn.Close()
    End Try

    Return u
End Function


'
' GetUserFromReader
'    A helper function that takes the current row from the OdbcDataReader
' and hydrates a MembershiUser from the values. Called by the 
' MembershipUser.GetUser implementation.
'

Private Function GetUserFromReader(ByVal reader As OdbcDataReader) As OdbcMembershipUser
    Dim providerUserKey As Object = reader.GetValue(0)
    Dim username As String = reader.GetString(1)
    Dim email As String = reader.GetString(2)

    Dim passwordQuestion As String = ""
    If Not reader.GetValue(3) Is DBNull.Value Then _
      passwordQuestion = reader.GetString(3)

    Dim comment As String = ""
    If Not reader.GetValue(4) Is DBNull.Value Then _
      comment = reader.GetString(4)

    Dim isApproved As Boolean = reader.GetBoolean(5)
    Dim isLockedOut As Boolean = reader.GetBoolean(6)
    Dim creationDate As DateTime = reader.GetDateTime(7)

    Dim lastLoginDate As DateTime = New DateTime()
    If Not reader.GetValue(8) Is DBNull.Value Then _
      lastLoginDate = reader.GetDateTime(8)

    Dim lastActivityDate As DateTime = reader.GetDateTime(9)
    Dim lastPasswordChangedDate As DateTime = reader.GetDateTime(10)

    Dim lastLockedOutDate As DateTime = New DateTime()
    If Not reader.GetValue(11) Is DBNull.Value Then _
      lastLockedOutDate = reader.GetDateTime(11)

    Dim isSubscriber As Boolean = False
    If reader.GetValue(12) IsNot DBNull.Value Then _
      isSubscriber = reader.GetBoolean(12)

    Dim customerID As String = String.Empty
    If reader.GetValue(13) IsNot DBNull.Value Then _
      customerID = reader.GetString(13)

    Dim u As OdbcMembershipUser = New OdbcMembershipUser(Me.Name, _
                                          username, _
                                          providerUserKey, _
                                          email, _
                                          passwordQuestion, _
                                          comment, _
                                          isApproved, _
                                          isLockedOut, _
                                          creationDate, _
                                          lastLoginDate, _
                                          lastActivityDate, _
                                          lastPasswordChangedDate, _
                                          lastLockedOutDate, _
                                          isSubscriber, _
                                          customerID)

    Return u
End Function

Modify the UpdateUser Method

When working with a custom membership user type and a custom membership provider, implement an UpdateUser method that takes an object of type MembershipUser as input. In your implementation of the UpdateUser method, cast the supplied MembershipUser object as your custom membership user type to access the values of the additional properties and update them in the data store.

The following code example shows the modified UpdateUser method of the sample membership provider from How to: Sample Membership Provider Implementation, which has been updated to cast the supplied user as the custom membership user type from the Create a Custom Membership User section earlier in this topic.

Public Overrides Sub UpdateUser(ByVal user As MembershipUser)

    Dim conn As OdbcConnection = New OdbcConnection(connectionString)
    Dim cmd As OdbcCommand = New OdbcCommand("UPDATE Users " & _
            " SET Email = ?, Comment = ?," & _
            " IsApproved = ?, IsSubscriber= ?, CustomerID = ?" & _
            " WHERE Username = ? AND ApplicationName = ?", conn)

    Dim u As OdbcMembershipUser = CType(user, OdbcMembershipUser)

    cmd.Parameters.Add("@Email", OdbcType.VarChar, 128).Value = user.Email
    cmd.Parameters.Add("@Comment", OdbcType.VarChar, 255).Value = user.Comment
    cmd.Parameters.Add("@IsApproved", OdbcType.Bit).Value = user.IsApproved
    cmd.Parameters.Add("@IsSubscriber", OdbcType.Bit).Value = u.IsSubscriber
    cmd.Parameters.Add("@CustomerID", OdbcType.VarChar, 128).Value = u.CustomerID
    cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = user.UserName
    cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName


    Try
        conn.Open()

        cmd.ExecuteNonQuery()
    Catch e As OdbcException
        If WriteExceptionsToEventLog Then
            WriteToEventLog(e, "UpdateUser")

            Throw New ProviderException(exceptionMessage)
        Else
            Throw e
        End If
    Finally
        conn.Close()
    End Try
End Sub

Modify the CreateUser Method

When working with a custom membership user type and a custom membership provider, the custom membership provider must implement a CreateUser method that takes only the properties supported by the MembershipUser class as input. You can create an overload of the CreateUser method that takes additional property values as shown in the following code example.

However, this overload will not be called by the Membership class or controls that rely on the Membership class, such as the CreateUserWizard control. To call this method from an application, cast the MembershipProvider instance referenced by the Membership class as your custom membership provider type, and then call your CreateUseroverload directly.

If your application is using the CreateUserWizard control to add new users to your membership data source, you can customize the wizard steps of the CreateUserWizard control to include controls that retrieve the additional property values of your custom membership user. You can then handle the CreatedUser event of the CreateUserWizard control and add event code that does the following:

  • Retrieves the property values of the additional membership user.

  • Casts the membership user created by the CreateUserWizard control as your custom membership user type.

  • Sets the additional properties on the membership user.

  • Passes the updated user to the UpdateUser method of the Membership class. This will call the UpdateUser method of your custom provider (which is described in the Modify the UpdateUser Method section earlier in this topic) to add the additional property values to your data source.

NoteNote

For an example of modifying the steps of the CreateUserWizard, see How to: Customize the ASP.NET CreateUserWizard Control.

The following code example shows the modified CreateUser method of the sample membership provider from How to: Sample Membership Provider Implementation, which has been updated to return the custom membership user type from the Create a Custom Membership User section earlier in this topic. An overload has been created to take values for the additional properties of the custom membership provider as input.

'
' MembershipProvider.CreateUser
'

Public Overrides Function CreateUser(ByVal username As String, _
                                     ByVal password As String, _
                                     ByVal email As String, _
                                     ByVal passwordQuestion As String, _
                                     ByVal passwordAnswer As String, _
                                     ByVal isApproved As Boolean, _
                                     ByVal providerUserKey As Object, _
                                     ByRef status As MembershipCreateStatus) _
                          As MembershipUser
    Return Me.CreateUser(username, password, email, _
                         passwordQuestion, passwordAnswer, _
                         isApproved, providerUserKey, False, "", status)
End Function


'
' OdbcMembershipProvider.CreateUser -- returns OdbcMembershipUser
'

Public Overloads Function CreateUser(ByVal username As String, _
                                     ByVal password As String, _
                                     ByVal email As String, _
                                     ByVal passwordQuestion As String, _
                                     ByVal passwordAnswer As String, _
                                     ByVal isApproved As Boolean, _
                                     ByVal providerUserKey As Object, _
                                     ByVal isSubscriber As Boolean, _
                                     ByVal customerID As String, _
                                     ByRef status As MembershipCreateStatus) _
                          As OdbcMembershipUser

    Dim Args As ValidatePasswordEventArgs = _
      New ValidatePasswordEventArgs(username, password, True)

    OnValidatingPassword(Args)

    If Args.Cancel Then
        status = MembershipCreateStatus.InvalidPassword
        Return Nothing
    End If


    If RequiresUniqueEmail AndAlso GetUserNameByEmail(email) <> "" Then
        status = MembershipCreateStatus.DuplicateEmail
        Return Nothing
    End If

    Dim u As MembershipUser = GetUser(username, False)

    If u Is Nothing Then
        Dim createDate As DateTime = DateTime.Now

        If providerUserKey Is Nothing Then
            providerUserKey = Guid.NewGuid()
        Else
            If Not TypeOf providerUserKey Is Guid Then
                status = MembershipCreateStatus.InvalidProviderUserKey
                Return Nothing
            End If
        End If

        Dim conn As OdbcConnection = New OdbcConnection(connectionString)
        Dim cmd As OdbcCommand = New OdbcCommand("INSERT INTO Users " & _
               " (PKID, Username, Password, Email, PasswordQuestion, " & _
               " PasswordAnswer, IsApproved," & _
               " Comment, CreationDate, LastPasswordChangedDate, LastActivityDate," & _
               " ApplicationName, IsLockedOut, LastLockedOutDate," & _
               " FailedPasswordAttemptCount, FailedPasswordAttemptWindowStart, " & _
               " FailedPasswordAnswerAttemptCount, FailedPasswordAnswerAttemptWindowStart, " & _
               " IsSubscriber, CustomerID)" & _
               " Values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", conn)

        cmd.Parameters.Add("@PKID", OdbcType.UniqueIdentifier).Value = providerUserKey
        cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username
        cmd.Parameters.Add("@Password", OdbcType.VarChar, 255).Value = EncodePassword(password)
        cmd.Parameters.Add("@Email", OdbcType.VarChar, 128).Value = email
        cmd.Parameters.Add("@PasswordQuestion", OdbcType.VarChar, 255).Value = passwordQuestion
        cmd.Parameters.Add("@PasswordAnswer", OdbcType.VarChar, 255).Value = EncodePassword(passwordAnswer)
        cmd.Parameters.Add("@IsApproved", OdbcType.Bit).Value = isApproved
        cmd.Parameters.Add("@Comment", OdbcType.VarChar, 255).Value = ""
        cmd.Parameters.Add("@CreationDate", OdbcType.DateTime).Value = createDate
        cmd.Parameters.Add("@LastPasswordChangedDate", OdbcType.DateTime).Value = createDate
        cmd.Parameters.Add("@LastActivityDate", OdbcType.DateTime).Value = createDate
        cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName
        cmd.Parameters.Add("@IsLockedOut", OdbcType.Bit).Value = False
        cmd.Parameters.Add("@LastLockedOutDate", OdbcType.DateTime).Value = createDate
        cmd.Parameters.Add("@FailedPasswordAttemptCount", OdbcType.Int).Value = 0
        cmd.Parameters.Add("@FailedPasswordAttemptWindowStart", OdbcType.DateTime).Value = createDate
        cmd.Parameters.Add("@FailedPasswordAnswerAttemptCount", OdbcType.Int).Value = 0
        cmd.Parameters.Add("@FailedPasswordAnswerAttemptWindowStart", OdbcType.DateTime).Value = createDate
        cmd.Parameters.Add("@IsSubscriber", OdbcType.Bit).Value = isSubscriber
        cmd.Parameters.Add("@CustomerID", OdbcType.VarChar, 128).Value = customerID

        Try
            conn.Open()

            Dim recAdded As Integer = cmd.ExecuteNonQuery()

            If recAdded > 0 Then
                status = MembershipCreateStatus.Success
            Else
                status = MembershipCreateStatus.UserRejected
            End If
        Catch e As OdbcException
            If WriteExceptionsToEventLog Then
                WriteToEventLog(e, "CreateUser")
            End If

            status = MembershipCreateStatus.ProviderError
        Finally
            conn.Close()
        End Try


        Return GetUser(username, False)
    Else
        status = MembershipCreateStatus.DuplicateUserName
    End If

    Return Nothing
End Function

See Also

Community Additions

ADD
Show:
© 2014 Microsoft