Search code examples
identityserver4asp.net-identity-2

Identity Sever 4 - Users to change their Username/Email


I need to give users, once logged in, the ability to change their username/email address (same value) on their account... maybe in a similar way to changing the password. I've looked through the IdentityServer4 docs but see no mention of this ... The system is using ASP.net Identity for the user data storage.

  1. Is there an 'out of the box' option with IdentityServer4 to change username? (as it isn't in the docs I assume not)

  2. Can anyone suggest any examples of this being done already? When searching, there is surprisingly very little information on this.

  3. If no examples, can anyone suggest where to start?


Solution

  • If you are using Asp.Net Identity with IS4, then updating the username/email will be done through the Asp.Net Identity methods. In particular, this is done via the UserManager using two methods, SetUserNameAsync() and SetEmailAsync(). Assuming you already have an instance of UserManager (using DI is common), the code would look something like:

    // First get the user, in this example, by ID but also you can use FindByEmailAsync()
    var identityUser = await _userManager.FindByIdAsync(id.ToString());
    
    // Change the Username field
    var usernameResult = await _userManager.SetUserNameAsync(identityUser, user.Email);
    
    // Change the email field
    var emailResult = await _userManager.SetEmailAsync(identityUser, user.Email);
    

    You can then check the usernameResult.Succeeded and emailResult.Succeeded booleans for the result of the operations.

    You can implement this however you want. In my case, I created a separate "User Management" API endpoint on the IdentityServer4 instance (that's also protected by IS4 itself) that runs this code. If you are interested in a similar option, take a look at the docs on IS4 about creating your own endpoint: http://docs.identityserver.io/en/latest/topics/add_apis.html