Asp.Net CoreはCookieを利用してアイデンティティ認証を行います

1661 ワード

Cookie認証サービスの登録
 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();

四読取クッキー
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")]....