情報応用演習Ⅰ(2024)

【T8b】ASP.NET Core Identity の基礎(4/9)

プロジェクトタイプ(注意: 本文参照)
プロジェクト名T8b
ソリューション名PIT8
注意
  • 本ページの作業内容は 前のページまでの続き になっていることに注意せよ.
    • 先に前のページまでをすべて読み,指示されている作業を済ませてから本ページを読むこと.
    • プロジェクトの作成作業については準備作業を参照せよ.

8b-4. ASP.NET Core Identity のセットアップ

まずは, ASP.NET Core Identity を使用するためのセットアップを行おう. NuGetを使って以下のパッケージを探してインストールする.

パッケージソースパッケージ名本校執筆時1の安定版
nuget.orgMicrosoft.AspNetCore.Identity.UI8.0.3
Microsoft.AspNetCore.Identity.EntityFrameworkCore8.0.3

つぎに ASP.NET Core Identity 用のデータコンテキストラスを用意する.ここまでの通常のデータコンテキストクラスは, EF Core にあらかじめ定義されているDbContextクラス(Microsoft.EntityFrameworkCore名前空間)から 派生させていた.ASP.NET Core Identity 用のデータコンテキストクラスを定義するには,DbContextクラスの代わりに IdentityDbContextクラス(Microsoft.AspNetCore.Identity.EntityFrameworkCore名前空間) から派生させればよい.プロジェクト内の Data フォルダを右クリックして「追加」→「クラス」をクリックする. 作成するクラス名を訊かれるのでT8bIdentityContext(.csは省略可能)と入力して「追加」ボタンをクリックする. すると空のクラス定義が作られるので_の定義を書き込もう.

T8bIdentityContextクラスの定義
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
using Microsoft.AspNetCore.Identity.EntityFrameworkCore; // 追記
using Microsoft.EntityFrameworkCore;                     // 追記

namespace T8b.Data
{
    public class T8bIdentityContext : IdentityDbContext
    {
        public T8bIdentityContext(DbContextOptions<T8bIdentityContext> contextOptions)
            : base(contextOptions)
        { }
    }
}

T8bIdentityContextクラスは,IdentityDbContextクラスから派生させているだけの空のクラスである. 通常のデータコンテキストクラスでは,このクラス内にDbSet型の プロパティを定義しなければデータベースにテーブルが作られないが,IdentityDbContextクラスは はじめから表8b-3-1のエンティティのためのDbSet<TEntity>型のプロパティの定義を含んでいるため これだけで最低限必要なテーブル定義が生成される.

次に Program.cs を編集しよう. Program.cs に_に示す内容を追記する.

Program.csの変更内容1
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
using KnzwTech.AspNetCore.ResourceBasedLocalization;
using Microsoft.AspNetCore.Identity; // 追加
using Microsoft.EntityFrameworkCore;
using T8b.Data;

AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews(opt => opt.EnableDefaultErrorMessagesFromResource());

builder.Services.AddDbContext<T8bContext>(opt
    => opt.UseNpgsql(builder.Configuration.GetConnectionString(nameof(T8bContext))));

// Identity 用のデータコンテキストを追加する.
builder.Services.AddDbContext<T8bIdentityContext>(
    opt => opt.UseNpgsql(builder.Configuration.GetConnectionString(nameof(T8bIdentityContext))));

// ASP.NET Core Identity のセットアップ
builder.Services.AddIdentity<IdentityUser, IdentityRole>()
    .AddRoleManager<RoleManager<IdentityRole>>()
    .AddDefaultTokenProviders()
    .AddEntityFrameworkStores<T8bIdentityContext>();

// 認証にCookieを使用するための設定
builder.Services.ConfigureApplicationCookie(opt => {
    opt.LoginPath = "/Admin/Login";
    opt.LogoutPath = "/Admin/Logout";
    opt.AccessDeniedPath = "/Admin/AccessDenied";
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();

app.UseStatusCodePagesWithReExecute("/Home/AccessError/{0}");

app.UseRouting();

app.UseAuthentication(); // 認証を有効化する
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

16~18行目を見ると分かるように,Identity用のデータコンテキストクラスのための接続文字列も,既存のデータコンテキストクラスT8bContextと 同じくアプリケーションの設定から接続文字列を読み取るように記述している.このため appsettings.json に_に示す内容を追記しておこう.

appsettings.jsonの追記内容1
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "T8bContext": "Host=localhost;Port=5432;Username=t8b_user;Database=t8b_db;Password=bX89#TaNNH", // ←ここカンマを追記するの忘れないように!
    "T8bIdentityContext": "Host=localhost;Port=5432;Username=t8b_user;Database=t8b_db;Password=bX89#TaNNH"
  }
}

ここではT8bContextT8bIdentityContextとで同じ接続文字列を使いまわしている.アプリケーション内で 複数のデータコンテキストクラスを使用する場合でも,このように情報を一つのデータベースに集約することが可能である.

つぎにマイグレーションコードを作成しよう.アプリケーション内に複数のデータコンテキストクラスが存在している場合は, dotnet ef migrations add コマンドや dotnet ef database update コマンドを実行する際に マイグレーション生成や データベースへの適用対象となるデータコンテキストクラスの名前を明示的に指定する必要がある 点に注意が必要である. これらのコマンドでデータコンテキストクラス名を指定するには-cオプションを付加する.このオプションは-c データコンテキストクラス名の ようにして使用する.コマンドラインターミナル2_のコマンドを実行してデータベースに変更を反映させよう(_).

マイグレーション処理の生成と適用
PS> dotnet ef migrations add AddIdentity -c T8bIdentityContext
PS> dotnet ef database update -c T8bIdentityContext

実行したら pgAdmin でデータベースの変化も確認しておこう. pgAdmin を起動するか,もしくは pgAdmin がすでに起動中の場合は 「 Servers 」→「 PostgreSQL 16 」→「 Databases 」を右クリックして「 Refresh 」を実行する. 「 Databases 」→「 t8b_db 」→「 Schemas 」→「 public 」→「 Tables 」に,以下の12個のテーブルが含まれていることを確認しよう(_). AspNet~から始まるテーブルが ASP.NET Core Identity 用のテーブルである.

  • ASP.NET Core Identity 用のテーブル
    • AspNetRoleClaims
    • AspNetRoles
    • AspNetUserClaims
    • AspNetUserLogins
    • AspNetUserRoles
    • AspNetUserTokens
    • AspNetUsers
  • アプリケーション独自のテーブル
    • Circles
    • CircleAffiliation
    • Department
    • Student
  • Entity Framework Core の管理用のテーブル
    • __EFMigrationsHistory
マイグレーション処理の結果を確認

  1. 2024年3月15日時点 ↩︎

  2. タブのタイトルは「開発用PowerShell」もしくは「Developer PowerShell」となっている. ↩︎

Last updated on 2024-06-10
Published on 2024-06-10

Powered by Hugo. Theme by TechDoc. Designed by Thingsym.