配置Microsoft.AspNet.Identity以允许电子邮件地址作为用户名

问题描述 投票:115回答:13

我正在创建一个新的应用程序并开始使用EF6-rc1,Microsoft.AspNet.Identity.Core 1.0.0-rc1,Microsoft.AspNet.Identity.EntityFramework 1.0.0-rc1,Microsoft.AspNet.Identity .Owin 1.0.0-rc1等昨天和RTM发布时,我今天晚上通过NuGet更新了它们到RTM。

除了我到目前为止所完成的工作的一些代码更改,所有似乎都进展顺利,直到我尝试为应用程序创建本地用户帐户。

我一直在处理电子邮件地址作为用户名格式,发布候选人工作得很好,但现在在创建一个用户名的电子邮件地址的用户时,它会引发以下验证错误:

User name [email protected] is invalid, can only contain letters or digits.

我花了大约一个小时左右的时间来搜索有关配置选项的解决方案或文档,但无济于事。

有没有办法可以配置它以允许用户名的电子邮件地址?

asp.net asp.net-identity
13个回答
158
投票

你可以通过在UserManager上插入你自己的UserValidator,或者只是在默认实现上关闭它来允许这个:

UserManager.UserValidator = new UserValidator<TUser>(UserManager) { AllowOnlyAlphanumericUserNames = false }

0
投票

我也坚持这一点,因为这些天大多数时候用户名都是电子邮件,但我可以理解单独的电子邮件领域的原因。这些纯粹是我的想法/经验,因为我也找不到微软对此的说法。

请记住,Asp Identity纯粹是为了识别某人,您不必识别电子邮件,但是它们允许我们存储它,因为它构成了身份的一部分。在visual studio中创建新的Web项目时,您可以选择身份验证选项。

如果选择非空项目类型(如MVC)并将身份验证设置为“个人帐户”,则会为您提供用户管理的基本基础。其中一个包含在App_Start \ IdentityConfig.cs中看起来像这样的子类:

 // Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.
public class ApplicationUserManager : UserManager<ApplicationUser>
{
    public ApplicationUserManager(IUserStore<ApplicationUser> store)
        : base(store)
    {
    }

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
    {
        var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
        // Configure validation logic for usernames
        manager.UserValidator = new UserValidator<ApplicationUser>(manager)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };
    }
    //N.B rest of code removed
}

这告诉我们的是,微软打算让我们存储更复杂的用户名(参考AllowOnlyAlphaNumericUserNames = false),所以我们确实有混合信号。

这是从默认Web项目生成的这一事实为我们提供了一个良好的指示/指示(以及一种干净的方式),使我们能够输入用户名字段的电子邮件。它很干净,因为在使用Microsoft.OWIN上下文引导应用程序时,在App_Start \ Startup.Auth.cs中使用静态create方法。

这种方法唯一的缺点是你最终存储了两次电子邮件....哪个不好!


0
投票

正如您可能已经发现的那样(并且可以预期),2014年3月发布的ASP.NET Identity 2.0.0在框架中添加了此功能。

公告:http://blogs.msdn.com/b/webdev/archive/2014/03/20/test-announcing-rtm-of-asp-net-identity-2-0-0.aspx

完整的示例和教程,包括帐户确认:http://www.asp.net/identity/overview/features-api/account-confirmation-and-password-recovery-with-aspnet-identity


0
投票

如果您在帐户控制器中使用某种类型的IOC(我正在使用StructureMap),则需要在传入Usermanager时应用Hao Kung上面提到的修复:(我必须)。可能有一种方法可以在IOC设置中完成,但我不知道如何。

public AccountController(ApplicationUserManager userManager)
    {
        _userManager = userManager;
        _userManager.UserValidator = new UserValidator<ApplicationUser>(_userManager)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };

0
投票

我遇到了同样的问题。但最后我通过在我的方法中添加了下面的部分来解决了这个问题,而不是构造函数。

public void MyMethod(){

     UserManager<ApplicationUser> manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));


                    // Configure validation logic for usernames  
                    manager.UserValidator = new UserValidator<ApplicationUser>(manager)
                    {
                        AllowOnlyAlphanumericUserNames = false,
                        RequireUniqueEmail = true

                    };         

}

15
投票

这个的C#版本(在App_Code \ IdentityModels.cs中)是

public UserManager()
        : base(new UserStore<ApplicationUser>(new ApplicationDbContext()))
    {
        UserValidator = new UserValidator<ApplicationUser>(this) { AllowOnlyAlphanumericUserNames = false };
    }

8
投票

就我而言,使用ASP.NET Identity 2.0在VS 2013 C#,MVC 5.2.2中运行,解决方案是更新App_Start \ IdentityConfig.cs中的ApplicationUserManager构造函数,如下所示:

public ApplicationUserManager(IUserStore<ApplicationUser> store)
        : base(store)
    {
        this.UserValidator = new UserValidator<ApplicationUser>(this) { AllowOnlyAlphanumericUserNames = false };
    }

4
投票

如果您正在使用ASP.Net webforms并且正在尝试完成此操作,只需打开IdentityModels.vb / cs文件并在Public Class UserManager下,看起来如下:

Public Class UserManager
Inherits UserManager(Of ApplicationUser)

Public Sub New()
    MyBase.New(New UserStore(Of ApplicationUser)(New ApplicationDbContext()))
    Users = store
    UserValidator = New UserValidator(Of ApplicationUser)(Me) With {.AllowOnlyAlphanumericUserNames = False}
End Sub

Public Property Users() As IUserStore(Of ApplicationUser)
    Get
        Return m_Users
    End Get
    Private Set(value As IUserStore(Of ApplicationUser))
        m_Users = value
    End Set
End Property
Private m_Users As IUserStore(Of ApplicationUser)

End Class

3
投票

对于AspNet.Identity.Core 2.1及更高版本的用户,UserManager中的这些验证器是只读的。默认情况下允许使用电子邮件地址作为用户名,但如果需要进一步自定义用户名中的字符,可以在Startup.cs中执行此操作,如下所示:

public void ConfigureServices(IServiceCollection services)
{
    services.AddIdentity<ApplicationUser, IdentityRole>(options => {
        options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+/";
    });

    // ... etc
}

(由于遗产原因我需要'/'。)


1
投票

由于编码我自己的ApplicationUserManager:UserManager类对我不起作用(也许bc我使用的是Razor Pages,而不是MVC),这是另一个解决方案:在CofigureServices()的Startup.cs中,您可以配置身份选项,例如:

services.Configure<IdentityOptions>(options =>
{
  options.User.AllowedUserNameCharacters = 
  "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@";
  options.User.RequireUniqueEmail = true;
});

有关Microsoft docs中此主题的更多信息:https://docs.microsoft.com/de-de/aspnet/core/security/authentication/identity-configuration?view=aspnetcore-2.2


1
投票

我有同样的问题,当我尝试更改代码时,使UserName是该人的真实姓名而不是电子邮件,系统显示相同的错误消息“用户名ABC DEF无效,只能包含字母或数字“。我解决了将空格字符(在我最后的情况下)添加到AllowedUserNameCharacters的问题。

我使用Asp.Net Core 2.2和VS2017

这是我的代码

转到Startup.cs并编辑或添加“// user settings”下的行:

        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseMySql(Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity<ApplicationUser, ApplicationRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        services.Configure<IdentityOptions>(options =>
        {
            // Password settings.
            options.Password.RequireDigit = true;
            options.Password.RequireLowercase = true;
            options.Password.RequireNonAlphanumeric = true;
            options.Password.RequireUppercase = true;
            options.Password.RequiredLength = 6;
            options.Password.RequiredUniqueChars = 1;

            // Lockout settings.
            options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
            options.Lockout.MaxFailedAccessAttempts = 5;
            options.Lockout.AllowedForNewUsers = true;


            // User settings.
            options.User.AllowedUserNameCharacters =
                "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+ ";
            options.User.RequireUniqueEmail = false;
        });

        services.ConfigureApplicationCookie(options =>

0
投票

如果找不到IdentityConfig.cs,请用此代码替换AccountController构造函数。

public AccountController(UserManager<ApplicationUser> userManager)
{
UserManager = userManager;
UserManager.UserValidator = new UserValidator<ApplicationUser>(UserManager) 
  {
      AllowOnlyAlphanumericUserNames = false  
  };
}

0
投票

在我的情况下,我有一个使用身份验证的存储库类,这不允许我在用户名中使用“ - ”..修复在这里的构造函数内:

//-------------------------------------------------------
public AuthRepository()
//-------------------------------------------------------
{
    _ctx = new AuthContext();
    _userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(_ctx));
    _userManager.UserValidator = new UserValidator<IdentityUser>(_userManager)
    {
        AllowOnlyAlphanumericUserNames = false
    };
}
© www.soinside.com 2019 - 2024. All rights reserved.