背景
ASP.NET Core Identity を使用するとユーザー認証が簡単にできる。
デフォルトではEmailとパスワードを登録するだけだった。
それにユーザー名を加えたところ日本語対応していなかった。。。
解決策
デフォルトで使用できる文字は以下の通り
options.User.AllowedUserNameCharacters="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";ユーザー名を日本語対応させるために Startup.cs 内で options.User.AllowedUserNameCharacters = null; に変更する。
Startup.cs
publicvoidConfigureServices(IServiceCollectionservices){// .....services.Configure<IdentityOptions>(options=>{// User settings.options.User.AllowedUserNameCharacters=null;// null か "" で日本語にも対応する});}参考
- https://docs.microsoft.com/ja-jp/aspnet/core/security/authentication/identity?view=aspnetcore-3.1&tabs=visual-studio
- https://stackoverflow.com/questions/42748332/where-are-the-allowonlyalphanumericusernames-and-uservalidator-properites-in-asp
ASP.NET Core Identity使い方
Visual Studioでwebアプリケーションを作成する際に認証を追加するだけ。
コンソールで以下のコマンド実行
PM> Update-Database
登録画面にユーザー名追加
プロジェクトで右クリック→追加→新規スキャフォールディングアイテムの追加→IDを追加
Account/Registerを選択して追加
Areas\Identity\Pages\Account\Register.cshtml にユーザー名入力フォームを追加
Register.cshtml
<divclass="row"><divclass="col-md-4"><formasp-route-returnUrl="@Model.ReturnUrl"method="post"><h4>Create a new account.</h4><hr/><divasp-validation-summary="All"class="text-danger"></div>
@*UserName入力*@
<divclass="form-group"><labelasp-for="Input.UserName"></label><inputasp-for="Input.UserName"class="form-control"/><spanasp-validation-for="Input.UserName"class="text-danger"></span></div><divclass="form-group"><labelasp-for="Input.Email"></label><inputasp-for="Input.Email"class="form-control"/><spanasp-validation-for="Input.Email"class="text-danger"></span></div>
...
Areas\Identity\Pages\Account\Register.cshtml.cs でユーザー名にはEmailが登録されていたので変更する。
Register.cshtml.cs
publicclassRegisterModel:PageModel{//...publicclassInputModel{// UserName 追加[Required][Display(Name="UserName")]publicstringUserName{get;set;}[Required][EmailAddress][Display(Name="Email")]publicstringEmail{get;set;}//...}publicasyncTask<IActionResult>OnPostAsync(stringreturnUrl=null){returnUrl=returnUrl??Url.Content("~/");ExternalLogins=(await_signInManager.GetExternalAuthenticationSchemesAsync()).ToList();if(ModelState.IsValid){// UserName = Input.Email -> Input.UserName に変更varuser=newIdentityUser{UserName=Input.UserName,Email=Input.Email};varresult=await_userManager.CreateAsync(user,Input.Password);//...}}}