ごった煮

色々な事を書いてます

ASP.NET Core Identityをシンプルに使うための実装方法

ASP.NET Core Identiyは、アプリケーションにメンバーシップ機能を実装する仕組みとしては、かなり優秀です。 テンプレートでそのまま普通のメンバーシップ機能を使用可能です。

ですが、ロール機能など場合によって使わない機能もデフォルトで付いてくるため、それらを削除して使えるようにしてみます。

実装方法

今回は、認証付きのASP.NET Core テンプレートを使用します。

実装に必要な全コードは、以下のものです。 startup.csのConfigureServicesに以下を実装します。

            services.AddIdentityCore<IdentityUser>()
                .AddDefaultUI(UIFramework.Bootstrap4)
                .AddEntityFrameworkStores<ApplicationDbContext>();

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
                options.DefaultChallengeScheme = IdentityConstants.ApplicationScheme;
                options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
            })
            .AddCookie(IdentityConstants.ApplicationScheme, o =>
            {
                o.LoginPath = new PathString("/Account/Login");
                o.Events = new CookieAuthenticationEvents()
                {
                    OnValidatePrincipal = SecurityStampValidator.ValidatePrincipalAsync
                };
            })
            .AddCookie(IdentityConstants.ExternalScheme, o => 
            {
                o.Cookie.Name = IdentityConstants.ExternalScheme;
                o.ExpireTimeSpan = TimeSpan.FromMinutes(5.0);
            })
            .AddCookie(IdentityConstants.TwoFactorRememberMeScheme, o =>
            {
                o.Cookie.Name = IdentityConstants.TwoFactorRememberMeScheme;
            })
            .AddCookie(IdentityConstants.TwoFactorUserIdScheme, o =>
            {
                o.Cookie.Name = IdentityConstants.TwoFactorUserIdScheme;
                o.ExpireTimeSpan = TimeSpan.FromMinutes(5.0);
            });
            services.AddScoped<ISecurityStampValidator, SecurityStampValidator<IdentityUser>>();

AddIdentityCoreは、ユーザテーブルだけを指定可能なので、ユーザテーブルのみの実装でIdentityを使用可能です。

まとめ

無駄なコードがあると見通しが悪くなりがちなので、いらない機能は、削除してしまいましょう。