web-dev-qa-db-ja.com

カスタムプロパティでIdentityUserを拡張する方法

ユーザーが自分のWebサイトにログインするためにasp.net Identity 2.0を使用しています。このWebサイトでは、認証の詳細がSQLデータベースに保存されています。 Asp.net Identityは、多くのオンラインチュートリアルで見られるように、標準的な方法で実装されています。

ApplicationUserIdentityModelsクラスは、カスタムプロパティを含むように拡張されました。

public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager, string authenticationType)
    {
       CookieAuthenticationOptions.AuthenticationType
       var userIdentity = await manager.CreateIdentityAsync(this, authenticationType);
       return userIdentity;
    }
    //My extended property
    public string Code { get; set; }
}

新しいユーザーを登録するとき、CodeRegisterBindingModelカスタムプロパティを渡しますが、このカスタムプロパティをWebUsersテーブルに挿入する方法がわかりません。

私は怒鳴りましたが、実際にはこのプロパティをユーザー名とパスワードとともにテーブルに挿入しません。

var user = new ApplicationUser() { UserName = userName, Email = model.Email, Code=model.Code };

そして機能全体:

[AllowAnonymous]
[Route("Register")]
public async Task<IHttpActionResult> Register(RegisterBindingModel model)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var userName = !string.IsNullOrEmpty(model.UserName) ? model.UserName : model.Email;
        //I set it here but it doesn't get inserted to the table.
        var user = new ApplicationUser() { UserName = userName, Email = model.Email, Code=model.Code };

        IdentityResult result = await UserManager.CreateAsync(user, model.Password);

        if (!result.Succeeded)
        {
            return GetErrorResult(result);
        }

        return Ok();
    }

私は何が欠けていますか?私は同様の質問を見ていましたが、これに対する答えが見つかりませんでした。

22
user3378165

ユーザーにカスタムフィールドを追加するすべての手順を実行すると、タスクが正常に完了します。

ユーザーにカスタムフィールドを追加するすべての手順は次のとおりです。

  1. ASP.NET Webアプリケーションを作成します
  2. 必ず[〜#〜] mvc [〜#〜]を選択し、認証個人ユーザーアカウントを選択してください。
  3. Models folder→Open IdentityModels.csApplicationUser classに移動し、プロパティを追加します。

    public string Code { get; set; }
    
  4. プロジェクトを構築する
  5. [〜#〜] tools [〜#〜]メニュー→Nuget Package Managerに移動→Package Manager Consoleをクリック
  6. タイプEnable-Migrationsを押して Enter タスクが完了するまで待ちます。次のような応答が表示されます。

       Checking if the context targets an existing database...
       Code First Migrations enabled for project WebApplication1.
    
  7. タイプAdd-Migration "Code"を押して Enter タスクが完了するまで待ちます。次のような応答が表示されます。

    Scaffolding migration 'Code'. The Designer Code for this migration
    file includes a snapshot of your current Code First model. This
    snapshot is used to calculate the changes to your model when you
    scaffold the next migration. If you make additional changes to your
    model that you want to include in this migration, then you can
    re-scaffold it by running 'Add-Migration Code' again.
    
  8. タイプUpdate-Databaseを押して Enter タスクが完了するまで待ちます。次のような応答が表示されます。

    Specify the '-Verbose' flag to view the SQL statements being applied 
    to the target database.
    Applying explicit migrations: [201611132135242_Code].
    Applying explicit migration: 201611132135242_Code.
    Running Seed method.
    

    このステップでSQL Server Object Explorerを更新してデータベースに移動し、dbo.AspNetUsers列の下に、Codeフィールドが表示されます。どのデータベース、またはどのサーバーを探すべきかわからない場合は、Web.Configファイルを開き、次のような接続文字列を確認します。

    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-WebApplication1-20161114125903.mdf;Initial Catalog=aspnet-WebApplication1-20161114125903;Integrated Security=True"
    providerName="System.Data.SqlClient" />
    

    データソース(SQLサーバーインスタンス)とデータベース名である.mdfを確認できます。

  9. モデルフォルダー→開くAccountViewModels.csファイル→RegisterViewModelクラスに移動し、このプロパティを追加します:(EFv6のAPIv2では、以下を追加できますModelsフォルダーの行→AccountBindingModelsファイル→RegisterBindingModelクラス)

    public string Code { get; set; }
    
  10. Views folder→Account folder→Open Register.cshtmlファイルに移動し、他のフィールドの近くに、たとえばパスワードの下にこのコードを追加します。

    <div class="form-group">
        @Html.LabelFor(m => m.Code, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.Code, new { @class = "form-control" })
        </div>
    </div>
    
  11. Controllers folder→Open AccountController.cs file→http postでRegisterアクションに移動し、ユーザーを作成する行を次のように変更します。

    var user = new ApplicationUser { UserName = model.Email, Email = model.Email,
        Code= model.Code };
    
  12. プロジェクトを実行し、/Account/Register urlして、新しいユーザーを登録します。ユーザーを登録した後、再度データベースにアクセスして、dbo.AspNetUsersView Dataテーブルにアクセスすると、コードが保存されたことがわかります。

ダウンロード

ここで実際の例を複製またはダウンロードできます。

さらに読む-カスタムプロパティをIdentityRoleに追加する方法

新しいプロパティをIdentityRoleに追加する方法を知りたい場合は、 カスタムプロパティをIdentityRoleに追加する方法 をご覧ください。

58
Reza Aghaei

元の投稿は1歳以上なので、これが他の人に役立つことを願っています

Authentication Individual User Accounts」でプロジェクトをすでに作成している場合:

ソリューションエクスプローラーで、[プロジェクト]> [モデル]> [IdentityModels.cs]に移動します。

_public class ApplicationUser: IdentityUser_の下(最初のクラスでなければなりません)。

以下の私の例のように、public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)の後にカスタムプロパティを追加します。

_public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }
    **//add custom properties here - these are just examples**
    public bool SendEmails { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
_

次に、NuGet Packagemanagerを使用します。

  • enable-migrations(まだ行っていない場合)
  • add-migration [入力]
  • nameYourMigration [入力]
  • (移行ファイルを表示して、プロパティが追加されることを確認します)
  • データベースの更新[入力]
  • AspNetUsers dbテーブルをチェックして、プロパティが正しく追加されたことを確認します

これが役立つことを願っています。

6
ceterisdev

主な問題は、ApplicationUserクラスに新しいクレームを登録しないことです。

私は同じ問題を抱えていたので、CreateIdentityAsyncの後の数行で解決しました。

public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager, string authenticationType)
    {
       CookieAuthenticationOptions.AuthenticationType
       var userIdentity = await manager.CreateIdentityAsync(this, authenticationType);

       // Add custom user claims here
        userIdentity.AddClaim(new Claim("Code",this.Code));
       return userIdentity;
    }
    //My extended property
    public string Code { get; set; }
}
0
Salvador Nava