- 建立一個空的Asp.net Core 5.0專案
- 新增IdentityServer4
- IdentityServer4資料持久化
- 配置IdentityServer4證照
- 建立一個基於Jwt身份驗證的WebApi專案
- 小結
建立一個空的Asp.net Core 5.0專案


新增IdentityServer4元件

安裝完成後通過AddIdentityServer方法將相關的服務註冊到容器中,同時這裡返回一個builder用於繼續構建IdentityServer服務,如儲存、快取、加密相關的金鑰等等;

IdentityServer4資料持久化

這個問題的原因在於,IdentityServer4在進行授權時實際上是依賴一系列資料的,這些資料包括Client、Resource、Scope等,所以為了保證授權相關操作能夠完成,需要配置相關資料的儲存服務,IdentityServer4預設提供了測試基於記憶體的資料儲存,但一般只是用於測試目的:

關於資料持久化,在.net技術棧中可以想到的就是Entity Framework,同時IdentityServer4提供了名為:IdentityServer4.EntityFramework的包,它包含了相關的實體型別(IdentityServer4.EntityFramework.Storage)以及EF的DbContext。所以引入IdentityServer4.EntityFramework包就可以實現基於EF的資料持久化,另外也可以自己實現。
上圖中可以看到IdentityServer4關於EF的包有2個,但是實際上安裝IdentityServer4.EntityFramework就包含Storage這個包了:
安裝完成之後,我們可以在IdentityServer4.EntityFramework.Storage包中找到以下兩個DbContext型別:



然後就可以對IdentityServer的儲存進行配置了:
以上主要是對資料庫連結字串、資料庫版本、字符集以及資料庫遷移程式集進行配置,需要注意的是在對資料庫進行遷移的時候預設使用DbContext所在的程式集,而IdentityServer4提供的DbContext位於IdentityServer4.EntityFramework.Storage包裡面,所以為了能夠確保遷移檔案正常生成,所以需要將Startup所在的程式集設為遷移程式集(注:更適合的方式是專門建立一個資料庫遷移專案來作為遷移程式集,這樣資料庫遷移的相關內容可以單獨維護)。



注:-c和-o分別是-Context 和-OutputDir 的簡寫,在引數沒有二義性時可以使用簡寫。

執行資料庫更新命令後,資料庫將完成建立:

資料庫也就建立好了:
啟動程式,並訪問https://localhost:55006/.well-known/openid-configuration即可看到以下內容,證明IdentityServer4已經成功啟動了:

注:關於IdentityServer4的預設資料可通過命令“dotnet new -i IdentityServer4.Templates”先安裝IdentityServer4相關模板,然後使用“dotnet new is4ef”命令來建立,具體參考文件:https://identityserver4.readthedocs.io/en/latest/quickstarts/5_entityframework.html


設定API的授權訪問:

成功訪問,但是這裡有個小細節需要注意一下,就是當獲取到access token後,在token的有效期內,哪怕是把IdentityServer關閉,也能使用token正常訪問受保護資源,換句話說access token頒發後就與IdentityServer無關了,以上內容實際上是使用Asp.Net core 5.0以及IdentityServer4實現了一個基於客戶端證照(Client Credentials)的Oauth2.0授權流程,但IdentityServer提供的內容不僅於此,後續文章將會對該IdentityServer繼續完善,使其成為一個功能完善的身份驗證服務。