分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 运营维护

AspNetCore2身份验证

发布时间:2023-09-06 01:48责任编辑:郭大石关键词:暂无标签

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

AspNetCore2身份验证

原文地址:https://www.cnblogs.com/tangchun/p/8716715.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved