简体   繁体   English

如何自定义 ASP.NET Identity Core 用户名以允许特殊字符和空格

[英]How to customize ASP.NET Identity Core Username to allow special characters and space

I have changed my Register Action Method to accept user Name instead of Email.我已将注册操作方法更改为接受用户名而不是 Email。

if (ModelState.IsValid)
{
    var user = new ApplicationUser 
    {
        UserName = model.Name,
        Email = model.Email,
    };

But when I Enter Name in TextBox like Joe Smith It give me an error that is Invalid UserName .但是当我像Joe Smith这样在 TextBox 中输入名称时,它给了我一个错误,即Invalid UserName It is not allowing user Name to Accept White space.它不允许用户名接受空格。 My Question is how can I modify the builtin User Name to allow space and special characters.我的问题是如何修改内置用户名以允许空格和特殊字符。 I am using ASP.NET Core.我正在使用 ASP.NET 内核。

Thanks in Advance.提前致谢。

You can set user validation rules configuring identity with options in your Startup.cs.您可以使用 Startup.cs 中的选项设置用户验证规则来配置身份。

services.AddIdentity<ApplicationUser, IdentityRole>(options => {
    options.User.AllowedUserNameCharacters = "allowed characters here";
    options.User.RequireUniqueEmail = true/false;
});

Related resources:相关资源:

Configure Identity 配置身份

So cloudikka's answer had it right.所以 cloudikka 的回答是对的。 I'll just add explicitly (cloudikka's link explained it as well) that you need to list ALL the characters you want to allow (not just the whitespace or special characters), like this:我将明确添加(cloudikka 的链接也对此进行了解释)您需要列出您想要允许的所有字符(不仅仅是空格或特殊字符),如下所示:

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

and NOT this options.User.AllowedUserNameCharacters = " ";而不是这个options.User.AllowedUserNameCharacters = " "; which means 'only whitespace characters allowed'.这意味着“只允许空格字符”。 (I reckon this was Babar's problem.) (我认为这是巴巴尔的问题。)

services.AddIdentity<ApplicationUser, IdentityRole>(options => { options.User.AllowedUserNameCharacters = String.Empty; options.User.RequireUniqueEmail = true; })
            .AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();

The proposed solution can be tricky if you have an exhaustive list of special characters to whitelist.如果您有要列入白名单的详尽特殊字符列表,则建议的解决方案可能会很棘手。

If you want to blacklist instead, disable the whitelist in startup.cs:如果要改为黑名单,请在 startup.cs 中禁用白名单:

 services.AddIdentity<User, Role>(
                options =>
                {                        
                    options.User.AllowedUserNameCharacters = string.Empty;
                })

Then create your custom user validator然后创建您的自定义用户验证器

 public class UsernameValidator<TUser> : IUserValidator<TUser>
where TUser : User
{
    public Task<IdentityResult> ValidateAsync(UserManager<TUser> manager, TUser user)
    {                
        if (user.UserName.Any(x=>x ==':' || x == ';' || x == ' ' || x == ','))
        {
            return Task.FromResult(IdentityResult.Failed(new IdentityError
            {
                Code = "InvalidCharactersUsername",
                Description = "Username can not contain ':', ';', ' ' or ','"
            }));
        }
        return Task.FromResult(IdentityResult.Success);
    }        
}

Then add it to startup.cs:然后将其添加到startup.cs:

 services.AddIdentity<User, Role>(
                options =>
                {
                    options.Password = new PasswordOptions
                    {
                        RequiredLength = 8,
                        RequireUppercase = true,
                        RequireNonAlphanumeric = true,
                        RequireDigit = true,
                        RequireLowercase = true
                    };
                    options.User.AllowedUserNameCharacters = string.Empty;
                }).AddUserValidator<UsernameValidator<User>>()

This is one of the problems caused by the en-US default mindset of most application developers..这是大多数应用程序开发人员的 en-US 默认思维方式导致的问题之一。

I generated a small class that does this for me like so...我生成了一个小的 class 像这样为我做这个......

options.User.AllowedUserNameCharacters =Utilities.GetAllWritableCharacters(encoding: System.Text.Encoding.UTF8);

the helper class contains the GetAllWritableCharacters method like so助手 class 包含 GetAllWritableCharacters 方法,如下所示

public class Utilities
{
    public static string GetAllWritableCharacters(Encoding encoding)
    {
        encoding = Encoding.GetEncoding(encoding.WebName, new EncoderExceptionFallback(), new DecoderExceptionFallback());
        var sb= new StringBuilder();
         
        char[] chars = new char[1];
        byte[] bytes = new byte[16];

           
        for (int i = 20; i <=  char.MaxValue; i++)
        {
            chars[0] = (char)i;
            try
            {
                int count = encoding.GetBytes(chars, 0, 1, bytes, 0);

                if (count != 0)
                {
                    sb.Append(chars[0]);
                }
            }
            catch 
            {
                break;
            }
        }
        return sb.ToString();
    }
}

now you can accept all meaningful characters from a character set including spaces and "exotic" letters现在您可以接受字符集中所有有意义的字符,包括空格和“奇异”字母

services.AddIdentity<AppUser, AppRole>(opts =>
        {

            opts.User.RequireUniqueEmail = true;
            opts.User.AllowedUserNameCharacters =
            "abcçdefgğhijklmnoöpqrsştuüvwxyzABCÇDEFGĞHIİJKLMNOÖPQRSŞTUÜVWXYZ0123456789-._";
            opts.Password.RequiredLength = 4;
            opts.Password.RequireNonAlphanumeric = false;
            opts.Password.RequireLowercase = false;
            opts.Password.RequireUppercase = false;
            opts.Password.RequireDigit = false;
        }).AddPasswordValidator<CustomPasswordValidator>().AddEntityFrameworkStores<AppIdentityDbContext>();

You can basically enter any character you want between two quotes.您基本上可以在两个引号之间输入您想要的任何字符。 options.User.AllowedUserNameCharacters = " "; options.User.AllowedUserNameCharacters = " ";

用户名不应允许特殊字符或空格,我认为没有任何网站允许您这样做,您可以使用名字和姓氏来获取诸如“Joe Smith”之类的信息。

As mentioned by @Jaffal the UserName should not allow special characters or white spaces.正如@Jaffal 所提到的,用户名不应允许特殊字符或空格。 It should be considered as a unique user identifier (aka nickname or email).它应该被视为唯一的用户标识符(又名昵称或电子邮件)。 To get nicely displayed user name you might want to introduce a new property.为了得到很好地显示的用户名,您可能需要引入一个新属性。

Eg add a new property called Name or in some other implementation may be two fields GivenName and FamilyName .例如,添加一个名为Name的新属性,或者在其他一些实现中可能是两个字段GivenNameFamilyName And ask user to fill in her name to these fields.并要求用户在这些字段中填写她的名字。

To extend the database with the extra field(s) your migration can be:要使用额外字段扩展数据库,您的迁移可以是:

public partial class ApplicationUserNamePropertyAdded : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.AddColumn<string>(
            name: "Name",
            table: "AspNetUsers",
            nullable: true);
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropColumn(
            name: "Name",
            table: "AspNetUsers");
    }
}

In your code when you Register a new user using ASP.NET Identity classes you will have a code line like:在您使用 ASP.NET Identity 类注册新用户时的代码中,您将有如下代码行:

var user = new ApplicationUser { UserName = model.Email, Email = model.Email, Name = model.Name };

Basically, the user's UserName will always be the same as Email and another Name property will be used for displaying purposes.基本上,用户的UserName将始终与 Email 相同,另一个Name属性将用于显示目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何自定义ASP.NET Identity Core用户名以在注册时允许特殊字符和空格 - How to customize ASP.NET Identity Core Username to allow special characters and space while registering 具有特殊字符的ASP.NET MVC标识电子邮件/用户名 - ASP.NET MVC Identity Email/Username with Special Characters ASP.NET Identity用户名中的特殊语言字符 - Special language characters in username of ASP.NET Identity 如何在 ASP.NET Core 中为 React SPA 自定义身份控制器? - How to customize Identity controller for React SPA in ASP.NET Core? .NET Core Identity - 无法使用包含特殊字符的用户名进行身份验证 - .NET Core Identity - Unable to authenticate with username containing special characters 如何在ASP.NET Core Mvc中将Unicode字符用作UserName? - How to take Unicode characters as UserName in ASP.NET Core Mvc? 如何自定义ASP.Net身份 - How should customize ASP.Net Identity 最佳实践:自定义asp.net core身份授权 - best practice: customize asp.net core identity authorization ASP.Net Core 2.1 中的身份&lt; - 自定义 AccountController - Identity in ASP.Net Core 2.1< - Customize AccountController 自定义 Asp.NET Core Identity Unauthorized Response Type 和 Statuscode - Customize Asp.NET Core Identity Unauthorized Response Type and Statuscode
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM