发布时间:2022-04-03 18:05:18来源:本站阅读(827)
.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
1543
1102
1855
2053
3677
2450
1112
1045
1361
1762
10271
6293
5834
5407
4904
4606
3821
3677
3643
3559