ASP.NET Core身份验证
asp.net core 身份验证
本文旨在演示如果使用内置的 identity 实现 asp.net core 的身份验证,不会进行其它扩展。本文将通过最简单的代码演示如何进行登录和身份验证操作。
使用Authentication
我们创建好 asp.net core 项目以后,需要在ConfigureServices中添加Authentication的服务配置,代码如下:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o => { o.LoginPath = new PathString("/Account/Login"); o.AccessDeniedPath = new PathString("/Account/AccessDenied"); });
然后,在Configure中添加上如下代码,注意,UseAuthentication要放在UseMvc前面。
app.UseAuthentication(); app.UseMvc().UseMvcWithDefaultRoute();
添加Account控制器
在完成第一步后,我们需要添加一个控制器,来进行登录、退出等操作,通常把这些功能放在AccountController中。关键代码如下:
/// <summary> /// 登录页面 /// </summary> /// <returns></returns> public IActionResult Login() { return View(); } /// <summary> /// 模拟登录 /// </summary> /// <param name="userName"></param> /// <returns></returns> [HttpPost] public async Task<IActionResult> Login(string userName) { //根据登录名获取用户身份,以及判断密码等操作 var user = new SysUserIdentity { Name = userName, IsAuthenticated = true }; if (user != null) { user.AuthenticationType = CookieAuthenticationDefaults.AuthenticationScheme; var identity = new ClaimsIdentity(user); identity.AddClaim(new Claim(ClaimTypes.Name, user.Name)); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity)); return Redirect("/Account"); } ViewBag.Errormessage = "登录失败,用户名密码不正确"; return View(); } /// <summary> /// 退出登录 /// </summary> /// <returns></returns> public async Task<IActionResult> Logout() { await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); return Redirect("/Account"); }
每一个Action的作用如下:
- Login - Get:用来响应Get请求,提供用户输入用户名、密码的页面。
- Login - Post:用来响应Post请求,对用户输入的用户名和密码进行验证,验证通过后分发票据
- Logout - Get:用来响应Get请求,退出登录。
获取用户身份
当用户通过上面的代码登录以后,在用户访问其它页面时,我们需要获取到用户的身份,为了演示如何获取到身份信息,我们想AccountController中添加一个Index页面,代码如下:
/// <summary> /// 获取登录人信息 /// </summary> /// <returns></returns> [Authorize] public async Task<IActionResult> Index() { var auth = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme); if (auth.Succeeded) { string userName = auth.Principal.Identity.Name; //重新获取用户身份 var user = new SysUserIdentity() { Name = userName, IsAuthenticated = true }; return View(user); } return Redirect("~/Account/Login"); }
本文作者:拓荒者IT
本文链接:https://www.cnblogs.com/youring2/p/10886129.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
📌做了个微信公众号【拓荒者IT】,分享各种技术干货,新内容首发到公众号,欢迎关注❤️
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步