发布时间:2022-04-03 18:05:18来源:本站阅读(795)
.NET一直有自带Authorize验证,在FRAMEWORK时就一直使用,方便好用。
下面说下在.NET CORE中的使用,使用COOKIES验证
首先看下program的代码
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(o =>
{
o.LoginPath = new PathString("/Home/Admin");
o.LogoutPath = new PathString("/Home/Admin");
o.AccessDeniedPath = new PathString("/Home/Admin");
o.Cookie.HttpOnly = true;
o.ExpireTimeSpan = new TimeSpan(8, 0, 0);
});
app.UseAuthentication();
app.UseAuthorization();
然后看下登录的后台代码
var user = _admin.Value.Login(u, p);
var claims = new List { new Claim("adminUser", JsonSerializer.Serialize(user)) };
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var adminUser = new ClaimsPrincipal(claimsIdentity);
HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, adminUser).Wait();
最后在要验证的 controller或action上面加下以下代码
[Authorize(AuthenticationSchemes= CookieAuthenticationDefaults.AuthenticationScheme)]
OK,搞定
注意:Authorize 后面括号里的一定要加
关键字: Authorize
上一篇: lambda中使用SUM
下一篇: .NET6 WEB API使用JWT
1898
1112
2016
1735
1137
1557
4539
1580
486
1162
10146
6236
5784
5356
4842
4539
3745
3589
3589
3499