Bertvan
Bertvan

Reputation: 5033

ASP.NET MVC4 WebMatrix WebSecurity Forms authentication: Changing a username

I'm using WebMatrix WebSecurity for my application's Forms Authentication.

The user needs to be able to change his username, without being logged out.

I supposed calling WebSecurity.Logout(), followed by WebSecurity.Login() would do the trick, but Login() requires a password. Of course, I cannot provide this password as it is hashed in the DB.

How can I make this requirement work?

EDIT: Below are a few suggestions on how to fix the issue of changing the username.

However, my actual problem was that the cookie still holds the old username. I found the following instructions on how to handle that:

http://omaralzabir.com/how_to_change_user_name_in_asp_net_2_0_membership_provider/

Upvotes: 2

Views: 2697

Answers (3)

Jesse Seger
Jesse Seger

Reputation: 960

So this is how I able to change the user name. This all happens inside a post action method for updating all kinds of user data.

First I check to see if the user name already exists. "info" is a model object coming from the view.

if (WebSecurity.CurrentUserName != info.UserName && 
   this.userRepository.Find(info.UserName) != null)
{
    ModelState.AddModelError("", "This email is already taken.");
    return View();
}

Then I update the database.

UserProfile user = this.userRepository.Find(info.UserId);
user.UserName = info.UserName;
this.userRepository.SaveUser(user);

Then here is the magic part. You have to reset the authorization cookie.

 FormsAuthentication.SetAuthCookie(user.UserName, false);

I hope that helps someone out there.

Upvotes: 3

Saravanan
Saravanan

Reputation: 7844

You can do the following steps

  1. Get the UserDetails by UserId or UserName
  2. Change the UserName
  3. Now update the user data by calling the SimpleMembershipProvider.UpdateUser.

More details here

Upvotes: 0

Robert McKee
Robert McKee

Reputation: 21477

Since WebMatrix WebSecurity is done via UserId, not Username, just change the data in the table you are storing your userdata in, and then redirect them to a new page. You don't need to log them out and back in, I believe the new username will be picked up immediately.

Upvotes: 2

Related Questions