发布时间:2022-04-03 18:05:18来源:本站阅读(883)
.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
1239
1151
1820
1751
1527
1226
1144
1817
1697
1847
10482
6391
5950
5508
5014
4700
3947
3822
3755
3665