Asp.Net Core 利用Cookie做身份认证

一 注册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")]....

猜你喜欢

转载自blog.51cto.com/12268222/2424329