in .NET Framework

Change username in ASP.NET Membership Provider

Found a great article here about the process of changing the username with the ASP.NET Membership Provider.

Here is a summary of the process that I found best useful which is one of the comments:

1. Make sure New UserName is Unique

2. Update the aspnet_Users table directly

3. Execute to following code to change the username/cookie/identity without leaving the webpage…

‘ Obtains the name of the FormsAuthentication Cookie, uses that name to request the Cookie and Decrypts the Cookies information into a AuthTicket

Dim AuthTicket As FormsAuthenticationTicket = FormsAuthentication.Decrypt(HttpContext.Current.Request.Cookies(FormsAuthentication.FormsCookieName).Value)

‘ Instantiates a new user identity authenticated using forms authentication based on the FormsAuthenticationTicket.

‘ The FormsAuthenticationTicket has been created using the exact same parameters of the user with the Old Username except the Old Username has been updated with the New Username.

Dim NewFormsIdentity As New FormsIdentity(New FormsAuthenticationTicket(AuthTicket.Version, NewUsername, AuthTicket.IssueDate, AuthTicket.Expiration, AuthTicket.IsPersistent, AuthTicket.UserData))

‘ Parse out the AuthTicket’s UserData into a string array of Roles

Dim Roles As String() = AuthTicket.UserData.Split(“|”.ToCharArray)

‘ Creates a new user that has the NewFormsIdentity and belongs to the array of Roles, if any, that was stored in the FormsAuthenticationTicket

Dim NewGenericPrincipal As New System.Security.Principal.GenericPrincipal(NewFormsIdentity, Roles)

‘ Sets the security information for the current HTTP request to the new user. The Username has now been changed (i.e. HttpContext.Current.User.Identity.Name = NewUsername, prior to this step is was the OldUsername)

HttpContext.Current.User = NewGenericPrincipal

‘ Removes the forms-authentication ticket from the browser

FormsAuthentication.SignOut()

‘ Cancels the current session

HttpContext.Current.Session.Abandon()

‘ Creates an authentication ticket for the supplied New Username and adds it to the cookies collection of the response or the URL

FormsAuthentication.SetAuthCookie(HttpContext.Current.User.Identity.Name, AuthTicket.IsPersistent)

4. Response.Redirect back to the same page if needed.

References:

http://omaralzabir.com/how_to_change_user_name_in_asp_net_2_0_membership_provider/