shuhelohelo’s blog

Xamarin.Forms多めです.

ASP.NET Coreの認証フレームワークIdentityを使う

youtu.be

環境

EntityFrameworkCoreのインストール

NugetからMicrosoft.EntityFrameworkCoreをインストールする.

f:id:shuhelohelo:20191117111830p:plain

使用するDBに応じてパッケージをインストールする

今回はSQLServerを使うので,Microsoft.EntityFrameworkCore.SqlServerをインストールする.

f:id:shuhelohelo:20191117112359p:plain

Identityのインストール

NugetからMicrosoft.AspNetCore.Identity.EntityFrameworkCoreをインストールする.

f:id:shuhelohelo:20191117105654p:plain

IdentityDbContextクラスを継承したクラスを作成する

        public AppDbContext(DbContextOptions<AppDbContext> options)
            : base(options)
        {

        }

すでにEntityFrameworkを使用している場合はDbContextを継承したクラスがあるので,親クラスをDbContextからIdentityDbContextに変更するだけでよい.

IdentityDbContextクラスはDbContextクラスを継承している.

サービスを追加する

Startup.cs内のConfigureServicesメソッド内で,Identityを使用するためのサービスを追加する.

        public void ConfigureServices(IServiceCollection services)
        {
            string connectionString = Configuration.GetConnectionString("OAuthDbConnection");
            
            services.AddDbContextPool<AppDbContext>(options =>
                options.UseSqlServer(connectionString));
            
            services.AddRazorPages();

            //これ.
            services.AddIdentity<IdentityUser, IdentityRole>()
                .AddEntityFrameworkStores<AppDbContext>();
        }

appsettings.jsonはこんなかんじ.GetConnectionStringsメソッドでここに記述した接続文字列を取得している。 この例はローカルのSqlServerExpressを使うようにしている。

  "ConnectionStrings": {
    "OAuthDbConnection": "Server=.\\SQLEXPRESS;Database=OAuthDB;Trusted_Connection=True;"
  }

Identityで使用するユーザーやロールなどの情報をEntityFrameworkを使って作成,操作するので,AddEntityFrameworkStoresをつなげている.

ミドルウェアを追加する

Configureメソッドに認証ミドルウェアを追加する.

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
//省略
            app.UseAuthentication();//これ
//省略
        }

EntityFrameworkCore.Designをインストール

これはマイグレーションを行うために必要.

f:id:shuhelohelo:20191117114448p:plain

EntityFrameworkCore.Toolsをインストール

これはAdd-MigrationなどのコマンドをPackage Manager Consoleで使えるようにするために必要.

f:id:shuhelohelo:20191117115626p:plain

Migration

Add-Migrationを実行する.

Update-Databaseを実行する.

これでDBにIdentity関連のいくつかのテーブルが作成される.

EFCoreの手順を書くのは何度目だろう....