ASP.NET Coreの認証フレームワークIdentityを使う
環境
EntityFrameworkCoreのインストール
NugetからMicrosoft.EntityFrameworkCore
をインストールする.
使用するDBに応じてパッケージをインストールする
今回はSQLServerを使うので,Microsoft.EntityFrameworkCore.SqlServer
をインストールする.
Identityのインストール
NugetからMicrosoft.AspNetCore.Identity.EntityFrameworkCore
をインストールする.
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をインストール
これはマイグレーションを行うために必要.
EntityFrameworkCore.Toolsをインストール
これはAdd-Migration
などのコマンドをPackage Manager Consoleで使えるようにするために必要.
Migration
Add-Migration
を実行する.
Update-Database
を実行する.
これでDBにIdentity関連のいくつかのテーブルが作成される.
EFCoreの手順を書くのは何度目だろう....