Asp.Net Core 利用Cookie作身份認證

一 註冊Cookie認證服務 ConfigureServicescookie

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(o=> {
                o.LoginPath = new PathString("/Home/Index");
                o.LogoutPath = new PathString("/Account/Login");
            } );

二 配置中間件 Configureapp

app.UseAuthentication(); //添加受權中間件 必須卸載app.UseMvc();以前。

三 登陸ide

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

四 讀取cookiecode

if (context.HttpContext.User.Identity.IsAuthenticated){
     var userName = context.HttpContext.User.FindFirst(ClaimTypes.Name).Value;
}

五 退出中間件

await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

六 其餘ip

[AllowAnonymous]   
    [Authorize]
         [Authorize(Roles = "Admin,IBusiness,IApproval")]....
相關文章
相關標籤/搜索