mohsinali1317
mohsinali1317

Reputation: 4425

Asp.NET identity issue

I am using asp.Identity to do the users and roles module in my application. I create user like this

var user = new ApplicationUser() { UserName = name, Email = email };
IdentityResult result1 = ApplicationUserManager.AppUserManager.Create(user, password);

It creates the user, the issue is that in the Application Manager it doesn't check for duplicate email. My application manager looks like this

public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
    {
        var manager = new ApplicationUserManager(new EntityUserStore<ApplicationUser, Account, ApplicationRole, Role>());

        AppUserManager = manager;

        // Configure validation logic for usernames
        manager.UserValidator = new UserValidator<ApplicationUser>(manager)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };
        // Configure validation logic for passwords
        manager.PasswordValidator = new PasswordValidator
        {
            RequiredLength = 6,
            RequireNonLetterOrDigit = false,
            RequireDigit = false,
            RequireLowercase = false,
            RequireUppercase = false,
        };
        var dataProtectionProvider = options.DataProtectionProvider;
        if (dataProtectionProvider != null)
        {
            manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
        }
        return manager;
}

The other is issue that, if I login using user name it works but if I use emal it returns null.

 ApplicationUser user = UserManager.FindByEmail(email); // this returns null

Anyone familiar with this issue?

Upvotes: 0

Views: 219

Answers (1)

Shawn Yan
Shawn Yan

Reputation: 183

Your ApplicationUserManager.AppUserManager.Create does not validate the email because you are not referring to the ApplicationUserManager context,which is something like this:

var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>(); 
var signInManager = Context.GetOwinContext().Get<ApplicationSignInManager>(); 
var user = new ApplicationUser() { UserName = name, Email = email }; 
IdentityResult result = manager.Create(user, password); 
if (result.Succeeded)

The above example var manager will contain the ApplicationUserManager context and validation of email will be done by RequireUniqueEmail = true.

Upvotes: 1

Related Questions