Search code examples
asp.netasp.net-web-apiasp.net-identityasp.net-identity-2

How should I add a user email address for a user with ASP.NET Identity 2


I have a WebAPI application and I would like to add an email to the information I store for each user. Although there are many examples out there I am not sure those are now the recommended way to go with Identity 2. In particular I notice that Identity 2 now has extension methods to deal with email.

UserManagerExtensions.FindByEmail Method

But how can I store the email so that I can use this extension method? Do I need to store it here and if so can I store it as a claim ?

public class ApplicationUser : IdentityUser {
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }
    // I don't want to add email here 
}

However I am not sure how to do this:

  • Should I some add the email into the above where it says "// Add custom user claims here" and if so then how would I do that?
  • Should I make a change to the registration method below and if so then how should I do that?

    [AllowAnonymous]
    [Route("Register")]
    public async Task<IHttpActionResult> Register(RegisterBindingModel model)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
    
        IdentityUser user = new IdentityUser
        {
            UserName = model.UserName
        };
    
        IdentityResult result = await UserManager.CreateAsync(user, model.Password);
        IHttpActionResult errorResult = GetErrorResult(result);
    
        if (errorResult != null)
        {
            return errorResult;
        }
    
        return Ok();
    }
    

I would appreciate some advice on how to do this. Note that I am using a token based approach with claims in an Identity2 application. If possible I am looking to do this with claims and not just by adding columns to the user table.


Solution

  • The IdentityUser class already contains a property for the email address, so there's no need to duplicate that. You only have to set that property during the registration process, similar to the following snippet

    IdentityUser user = new IdentityUser
    {
        UserName = model.UserName,
        Email = model.Email
    };
    

    Don't forget to extend your RegisterViewModel and the Register view with that additional property and field.