ASP.NET Core中實現(xiàn)用戶登錄驗證的最低配置示例代碼
前言
本文主要給大家介紹了關(guān)于ASP.NET Core用戶登錄驗證的最低配置的相關(guān)內(nèi)容,分享出來供大家參考學(xué)習(xí),下面話不多說了,來一起看看詳細的介紹:
背景是在一個項目中增加臨時登錄功能,只需驗證用戶是否登錄即可,所需的最低配置與實現(xiàn)代碼如下。
方法如下:
在 Startup 的 ConfigureServices() 方法中添加 Authentication 的配置:
services.AddAuthentication(options => { options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme; }).AddCookie();
在 Startup 的 Configure() 方法中將 Authentication 添加到請求管線:
app.UseAuthentication();
在登錄程序中驗證通過用戶名/密碼后,通過下面的代碼生成登錄 Cookie 并發(fā)送給客戶端:
var claimsIdentity = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, model.Email) }, "Basic"); var claimsPrincipal = new ClaimsPrincipal(claimsIdentity); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal);
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關(guān)文章
Coolite Cool Study 1 在Grid中用ComboBox 來編輯數(shù)據(jù)
作為Coolite的第一個教程,我想展現(xiàn)給大家能夠體現(xiàn)Coolite強大的例子(當然也比官方例子稍微復(fù)雜一點)。2009-05-05C#(.NET)數(shù)據(jù)訪問連接、查詢、插入等操作的封裝類
一個C#(.NET)數(shù)據(jù)訪問連接、查詢、插入等操作的封裝類2008-05-05