ASP.NET Core 实现用户登录验证的最低配置
2024-10-15 14:57:45
背景是在一个项目中增加临时登录功能,只需验证用户是否登录即可,所需的最低配置与实现代码如下。
在 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);
最新文章
- iOS Real Stuff
- document.cookie的使用
- boostrap中lg,md,sm,xs
- 【M8】了解各种不同意义的new和delete
- corejava-chap01
- SE 2014年5月9日
- bat文件无法双击运行
- Windows Phone 8 MD5
- 关于Two-Pass标记连通域个数
- Spring MVC CORS 跨域
- 什么是web框架
- spark streamingcontext
- socket实现FTP上传下载功能
- Linux_问题
- fpm...failed: Cannot assign requested address
- 洛谷P2057 【SHOI2007】善意的投票
- python类的全面介绍
- ob系列函数中常用函数
- 如何使用JDBC删除一条记录
- POJ3261(SummerTrainingDay10-G 后缀数组)