最近工作中遇到一个需求,需要在asp.net core中来实现一个基础的身份认证,下面这篇文章主要给大家介绍了关于asp.net core中实现用户登录验证的最低配置的相关资料,需要的朋友可以参考借鉴,下面来一起看看吧。
前言
本文主要给大家介绍了关于ASP.NET Core用户登录验证的最低配置的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍:
背景是在一个项目中增加临时登录功能,只需验证用户是否登录即可,所需的最低配置与实现代码如下。
方法如下:
在 Startup 的 ConfigureServices() 方法中添加 Authentication 的配置:
services.AddAuthentication(options => { options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme; }).AddCookie();
在 Startup 的 Configure() 方法中将 Authentication 添加到请求管线:
app.UseAuthentication();
在登录程序中验证通过用户名/密码后,通过下面的代码生成登录 Cookie 并发送给客户端:
var claimsIdentity = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, model.Email) }, "Basic"); var claimsPrincipal = new ClaimsPrincipal(claimsIdentity); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal);
总结
以上就是ASP.NET Core中用户登录验证实现最低配置的示例代码的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号