1. 將認證添加到服務中
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
//登入地址
options.LoginPath = "/Account/FcbLogin/";
//登出地址
options.LogoutPath = "/Account/FcbLogout/";
//設置cookie過期時長
//options.ExpireTimeSpan = TimeSpan.FromSeconds(10);
});
所有CookieAuthenticationOptions 屬性可以查看微軟官方文檔



2. 注入管道
這里認證要在授權之前注入
app.UseAuthentication();
3. 添加登入和登出
這里我沒有驗證用戶賬號密碼,只是寫了登入和登出的相關代碼,這里也可以喝注入認證那里一樣,這是票證過期時間
[HttpPost]
public async Task<ActionResult> Login(UserLogin model)
{
//這里的scheme一定要和注入服務的scheme一樣
var identity = new ClaimsIdentity(new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme));
//自定義的claim信息
identity.AddClaim(new Claim("abc", "123"));
AuthenticationProperties properties = new AuthenticationProperties()
{
//設置cookie票證的過期時間
ExpiresUtc = DateTime.Now.AddDays(1),
RedirectUri = model.ReturnUrl
};
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), properties);
if (string.IsNullOrEmpty(model.ReturnUrl))
{
return LocalRedirect("/");
}
return LocalRedirect(model.ReturnUrl);
}
[HttpGet]
public ActionResult FcbLoginOut()
{
//AuthenticationProperties properties = new AuthenticationProperties()
//{
// ExpiresUtc = DateTime.Now.AddDays(-100)
//};
HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Ok();
}
