421 字
2 分鐘
使用 IdentityServer4 + ASP.Net Identity 初始化專案流程
結論
用 is4aspid 範本 + Migration + Seed,一次完成 IdentityServer4 + 使用者系統初始化。
適合用在哪裡
- 需要快速建立 OAuth / OpenID Connect Server
- 想整合 ASP.NET Identity(帳密登入)
- 建立內部驗證服務或 SSO 系統
- 測試或學習 IdentityServer 架構
流程步驟
1. 安裝範本並建立專案
- 使用
dotnet new安裝 IdentityServer4 範本 - 建立整合 ASP.NET Identity 的專案(is4aspid)
- 為什麼:這個範本已內建登入、使用者管理,不用自己刻
# 安裝範本dotnet new -i identityserver4.templates
# 建立專案(含 ASP.NET Identity)dotnet new is4aspid -n IdentityServerAspNetIdentity常用範本簡單對照:
| 範本 | 用途 |
|---|---|
| is4empty | 空專案 |
| is4inmem | 記憶體測試 |
| is4ef | DB 儲存設定 |
| is4aspid | 整合帳密登入(推薦) |
2. 建立資料庫(Migration)
- 新增 Migration(產生資料表結構)
- 更新資料庫(建立 Identity + IdentityServer Tables)
- 為什麼:IdentityServer 需要 DB 存 client / user / config
# 建立 Migrationdotnet ef migrations add InitialCreate
# 建立資料表dotnet ef database update3. 初始化 Seed 資料
- 啟動專案時加
/seed參數 - 自動寫入測試使用者、Client 設定
- 為什麼:避免手動建資料,直接可測試登入流程
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/