文章出處

背景是在一個項目中增加臨時登錄功能,只需驗證用戶是否登錄即可,所需的最低配置與實現代碼如下。

在 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);

文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()