一 註冊Cookie認證服務 ConfigureServices
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(o=> {
o.LoginPath = new PathString("/Home/Index");
o.LogoutPath = new PathString("/Account/Login");
} );
二 配置中間件 Configure
app.UseAuthentication(); //添加授權中間件 必須卸載app.UseMvc();之前。
三 登錄
var claims = new[]
{
new Claim("UserName","AESCR"),
new Claim("Sex","男")
};
var claimsIdentity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, "AESCR"));
claimsIdentity.AddClaim(new Claim("密碼","6666"));
ClaimsPrincipal user = new ClaimsPrincipal(claimsIdentity);
HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, user,new AuthenticationProperties() {
IsPersistent = true,
AllowRefresh = true,
RedirectUri = "/Home/Index",
}).Wait();
四 讀取cookie
if (context.HttpContext.User.Identity.IsAuthenticated){
var userName = context.HttpContext.User.FindFirst(ClaimTypes.Name).Value;
}
五 退出
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
六 其他
[AllowAnonymous]
[Authorize]
[Authorize(Roles = "Admin,IBusiness,IApproval")]....