【问题标题】:Asp.NET identity issueAsp.NET 身份问题
【发布时间】:2016-06-28 18:00:34
【问题描述】:

我正在使用 asp.Identity 在我的应用程序中执行用户和角色模块。我创建这样的用户

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

它创建用户,问题是在应用程序管理器中它不检查重复的电子邮件。我的应用程序管理器看起来像这样

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;
}

另一个问题是,如果我使用用户名登录,它可以工作,但如果我使用 emal,它会返回 null。

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

有人熟悉这个问题吗?

【问题讨论】:

  • 假设如果result1 没有成功,那么你应该有一个ModelState.AddModelError("", "Invalid login attempt.");
  • 但它成功并创建了用户,即使电子邮件不是唯一的
  • 对于您使用电子邮件登录的问题,我建议您查看this
  • 我知道你为什么需要AppUserManager吗?
  • 我不明白这个问题,我的意思是这不是这样做的吗?我一直在关注一些教程,他们就是这样做的。

标签: c# asp.net


【解决方案1】:

您的 ApplicationUserManager.AppUserManager.Create 不会验证电子邮件,因为您没有引用 ApplicationUserManager 上下文,如下所示:

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)

上述示例 var manager 将包含 ApplicationUserManager 上下文,电子邮件验证将由 RequireUniqueEmail = true 完成。

【讨论】:

    猜你喜欢
    • 2015-03-30
    • 1970-01-01
    • 2022-11-14
    • 2014-12-18
    • 1970-01-01
    • 2021-02-11
    • 2017-08-24
    相关资源
    最近更新 更多