421 字
2 分鐘
瀏覽次數
使用 IdentityServer4 + ASP.Net Identity 初始化專案流程
2025-07-25
2026-04-13

結論#

is4aspid 範本 + Migration + Seed,一次完成 IdentityServer4 + 使用者系統初始化。

適合用在哪裡#

  • 需要快速建立 OAuth / OpenID Connect Server
  • 想整合 ASP.NET Identity(帳密登入)
  • 建立內部驗證服務或 SSO 系統
  • 測試或學習 IdentityServer 架構

流程步驟#

1. 安裝範本並建立專案#

  • 使用 dotnet new 安裝 IdentityServer4 範本
  • 建立整合 ASP.NET Identity 的專案(is4aspid)
  • 為什麼:這個範本已內建登入、使用者管理,不用自己刻
Terminal window
# 安裝範本
dotnet new -i identityserver4.templates
# 建立專案(含 ASP.NET Identity)
dotnet new is4aspid -n IdentityServerAspNetIdentity

常用範本簡單對照:

範本用途
is4empty空專案
is4inmem記憶體測試
is4efDB 儲存設定
is4aspid整合帳密登入(推薦)

2. 建立資料庫(Migration)#

  • 新增 Migration(產生資料表結構)
  • 更新資料庫(建立 Identity + IdentityServer Tables)
  • 為什麼:IdentityServer 需要 DB 存 client / user / config
Terminal window
# 建立 Migration
dotnet ef migrations add InitialCreate
# 建立資料表
dotnet ef database update

3. 初始化 Seed 資料#

  • 啟動專案時加 /seed 參數
  • 自動寫入測試使用者、Client 設定
  • 為什麼:避免手動建資料,直接可測試登入流程
Terminal window
dotnet run /seed

程式碼核心:

var seed = args.Contains("/seed");
if (seed)
{
args = args.Except(new[] { "/seed" }).ToArray();
}
var host = CreateHostBuilder(args).Build();
if (seed)
{
// 初始化資料
var config = host.Services.GetRequiredService<IConfiguration>();
var connectionString = config.GetConnectionString("DefaultConnection");
SeedData.EnsureSeedData(connectionString);
return 0;
}

補充#

  • IdentityServer4 已停止維護,正式專案建議評估 Duende(需付費)
  • Seed 只適合開發環境,正式環境請用 Migration + Script 控管
  • /seed 設計很方便,但要避免誤用在 Production

收尾#

三步驟搞定驗證系統初始化,重點不是寫程式,是選對範本。 工程上:先能跑,再優化。

使用 IdentityServer4 + ASP.Net Identity 初始化專案流程
https://joyceowo.github.io/posts/23ba78ea09fa81dc9fe8e63d47cb55ad/
作者
JoyceOwO
發佈於
2025-07-25
許可協議
CC BY-NC-SA 4.0