Scott Millett

Storing the UserID instead of the UserName in the User.Identity.Name Object when using the Login Control and MemberShip API

The problem I had wiith using the Membership API and the login Control was that by default after logging in the User.Identity.Name is set to the username that users logon with, and this is usually a string value i.e. their email address or username.

I wanted to store the user id in the User.Identity.Name varaible, this is how I acheieved it using the Membership Login Control:

Imports System.Web.Security
Imports System.Web.UI.WebControls
Imports MySite.BusinessFacade

Partial Class MembersArea_CustomerLogin
    
Inherits System.Web.UI.Page                 

    Protected
Sub Login1_LoggedIn(ByVal sender As Object, ByVal e As System.EventArgs)  _
              Handles Login1.LoggedIn
                    
              
Dim lngUserID As Long
              ' The UserFacade is the interface into my business layer
              
Dim aUserFacade As New UserFacade
              ' This method simply returns the UserID of the user that has just been 
              ' logged in. We get the Username from the login control text box. 
              
lngUserID = aUserFacade.getUserID(Login1.UserName)

              ' Now that we have got the UserID we need to recreate the 
              ' authentication ticket we removed earlier otherwise
              ' the user will not be authenticated.
              
Dim authTicket As FormsAuthenticationTicket = _
                            
New FormsAuthenticationTicket(lngUserID , False, 30)

              Dim encryptedTicket As String = FormsAuthentication.Encrypt(authTicket)

              Dim authCookie As HttpCookie = _
              
New HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)

              HttpContext.Current.Response.Cookies.Add(authCookie)
      End Sub

End Class

Now we can access the UserID where ever we want.

Dim aCustomerFacade As New CustomerFacade
Dim allProjects As List(Of Projects)

allProjects = aUserFacade.GetAllProjects(
CType(User.Identity.Name, Long))



 

Comments

Jacques said:

Thanks allot for your article, it really helped me. However, i did find that if one replaces the Identity.Name cookie value with the UserId, the latter will be displayed when using a asp:LoginName control to welcome the logged in user, i.e. you will see Welcome 456-456-rert-5645-re. Other than that your article helped me tons, thanks!

Jacques

# October 1, 2008 6:00 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)