AspNetCore2身份验证

本文介绍如何在ASP.NET Core应用中实现基于Cookies的身份验证流程,包括配置中间件、添加验证服务、实现登录与登出功能。

1、在Startup类的Configure方法,添加身份验证的中间件AuthenticationMiddleware

 app.UseAuthentication();

2、在Startup类的ConfigureServices方法,添加Cookie验证的服务,使用Cookies验证体系,

CookieAuthenticationDefaults.AuthenticationScheme="Cookies"

  services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
                {
                    options.AccessDeniedPath = "/Sys/Home/Index";
                    options.LoginPath = "/Sys/Home/Login";
                    options.Cookie.Name = "AuthCookie";
                    options.Cookie.Path = "/";
                    options.Cookie.Expiration = TimeSpan.FromMinutes(30);
                });

3、添加登录action,ClaimsIdentity(string authenticationType)的authenticationType必须和service设置的验证体系一样,才能正常验证,

 [HttpPost]
        [AllowAnonymous]
        public async Task<ActionResult> Login()
        {
            string AdminAccount = Request.Form["AdminAccount"];
            string Password = Request.Form["Password"];
            if (string.IsNullOrWhiteSpace(AdminAccount))
            {
                return JsonError("账号不能为空");
            }
            if (string.IsNullOrWhiteSpace(Password))
            {
                return JsonError("密码不能为空");
            }
            Admin admin = _context.Admins.FirstOrDefault(c => c.AdminAccount == AdminAccount && c.Password == Password);
            if (admin == null)
            {
                return JsonError("用户名或者密码错误");
            }
            ClaimsIdentity identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
            identity.AddClaim(new Claim(ClaimTypes.Name, admin.Id.ToString()));
            await HttpContext.SignInAsync(new ClaimsPrincipal(identity));
            return JsonSuccess();
        }

4、在需要验证的控制器上加[AuthorizeAttribute]特性,通过HttpContext.User.Identity.IsAuthenticated可判断用户是否已通过验证

5、退出登录Action

 /// <summary>
        /// 退出登录
        /// </summary>
        /// <returns></returns>
        public async Task<ActionResult> SignOut()
        {
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return JsonSuccess();
        }

 

转载于:https://www.cnblogs.com/tangchun/p/8716715.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值