文章出處
文章列表
背景是在一個項目中增加臨時登錄功能,只需驗證用戶是否登錄即可,所需的最低配置與實現代碼如下。
在 Startup 的 ConfigureServices() 方法中添加 Authentication 的配置:
services.AddAuthentication(options => { options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme; }).AddCookie();
在 Startup 的 Configure() 方法中將 Authentication 添加到請求管線:
app.UseAuthentication();
在登錄程序中驗證通過用戶名/密碼后,通過下面的代碼生成登錄 Cookie 并發送給客戶端:
var claimsIdentity = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, model.Email) }, "Basic"); var claimsPrincipal = new ClaimsPrincipal(claimsIdentity); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal);
文章列表
全站熱搜