用戶必須進行登錄,才能夠讓 IdentityServer 發出 Token
一.Cookie認證
使用 ASP.NET Core 的 Cookie 認證(傳送門)
IdentityServer 注冊了兩個cookie處理程序(一個用於身份驗證會話,另一個用於臨時的外部cookie)。 它們默認使用,如果你想手動引用它們,您可以從IdentityServerConstants
類(DefaultCookieAuthenticationScheme
和ExternalCookieAuthenticationScheme
)獲取它們的名稱。
IdentityServer 只公開這些cookies的基本設置(過期和滑動),如果你需要更多的控制,你可以注冊你自己的cookie處理程序。 當使用了 ASP.NET Core 的AddAuthentication
方法時,IdentityServer 會使用與AddAuthentication
添加的AuthenticationOptions
上的DefaultAuthenticateScheme
相匹配的 cookie 處理程序。
二.重寫cookie處理程序配置
如果你想使用你自己的cookie身份驗證處理程序,那么你必須自己配置它。 在DI中注冊身份服務器(使用AddIdentityServer
)后,必須在ConfigureServices
中完成此操作。 例如:
services.AddIdentityServer()
.AddInMemoryClients(Clients.Get())
.AddInMemoryIdentityResources(Resources.GetIdentityResources())
.AddInMemoryApiResources(Resources.GetApiResources())
.AddDeveloperSigningCredential()
.AddTestUsers(TestUsers.Users);
services.AddAuthentication("MyCookie")
.AddCookie("MyCookie", options =>
{
options.ExpireTimeSpan = ...;
});
IdentityServer 內部使用自定義方案(通過常量
IdentityServerConstants.DefaultCookieAuthenticationScheme
)調用AddAuthentication
和AddCookie
,因此要覆蓋它們,必須在AddIdentityServer
之后進行相同的調用。
三.登錄用戶界面和身份管理系統
IdentityServer 本身不提供任何用戶界面或用戶數據庫。 這些都需要你自己實現或者使用其他實現。
如果您需要基本用戶界面(登錄,注銷,同意和管理授權)的快速入門,則可以使用IdentityServer提供的的quickstart UI。
quickstart UI根據內存數據庫對用戶進行認證。 你想取代這些那么請使用你的真實用戶存儲。 IdentityServer 有配合 ASP.NET Identity 的示例。
四.登錄工作流程
當 IdentityServer 在授權終結點(connect/token)收到請求,且用戶沒有通過認證時,用戶將被重定向到配置的登錄頁面。 您必須通過設置UserInteraction
(默認為/ account / login)來通知IdentityServer您的登錄頁面的路徑。 同時將會傳遞一個returnUrl參數,通知你的登錄頁面,一旦登錄完成,用戶應該被重定向到哪里。
注意通過returnUrl參數的開放重定向攻擊。 你應該驗證這個returnUrl指的是已知的位置。 請參閱API的交互服務來驗證returnUrl參數(https://identityserver4.readthedocs.io/en/release/reference/interactionservice.html#refinteractionservice)。
五.登錄上下文
在你的登錄頁面上,您可能需要有關請求上下文的信息,以便自定義登錄體驗(如客戶端,提示參數,IdP提示或其他內容)。 這可以通過交互服務上的GetAuthorizationContextAsync
API獲得(https://identityserver4.readthedocs.io/en/release/reference/interactionservice.html#refinteractionservice)。
六.發出一個cookie和身份信息單元(Claim)
在 ASP.NET Core 的HttpContext
上有與身份驗證相關的擴展方法來發布身份驗證cookie並簽署用戶。所使用的身份驗證方案必須與您正在使用的cookie處理程序(請參閱上文)匹配。
當用戶登錄時,你必須至少發出一個sub
身份單元和一個name
身份單元。 IdentityServer還在HttpContext上提供了一些SignInAsync
擴展方法,來方便使用。
您還可以選擇發出idp
身份信息單元(針對身份提供者名稱,例如:QQ),amr
身份信息單元針對使用的身份驗證方法)或者auth_time
身份信息單元(表示用戶認證的認證時間)。 如果你不設置這些,IdentityServer將設置為默認值。