Asp.Net Core done using the Cookie Authentication

Cookie a registered certification services ConfigureServices

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

Configure two middleware configuration

app.UseAuthentication(); //添加授权中间件 必须卸载app.UseMvc();之前。

Three Login

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

Four read cookie

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

Five exits

 await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

The other six

    [AllowAnonymous]   
    [Authorize]
         [Authorize(Roles = "Admin,IBusiness,IApproval")]....

Guess you like

Origin blog.51cto.com/12268222/2424329