我正在尝试根据 Cookies 按角色(Admin\User)创建授权 添加了添加默认身份并启用了 UseAuthentication 和 UseAuthorization 身份验证有效,.net 从数据库中看到角色,但不允许用户或管理员进入 User.IsInRole("Admin")
字段数据取自Users表,其中有角色字段和
课程计划
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<StoreContext>();
builder.Services.AddControllersWithViews();
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<StoreContext>();
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = new PathString("/Account/Login");
options.AccessDeniedPath = new PathString("/Account/Login");
});
builder.Services.AddAuthentication();
builder.Services.AddAuthorization();
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
}
账户控制器
private StoreContext _storeContext;
public AccountController(StoreContext context)
{
_storeContext = context;
}
[Authorize(Roles = "Admin")]
public IActionResult a()
{
return View();
}
[HttpGet]
public IActionResult Register()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegModel model)
{
if (ModelState.IsValid)
{
User user = await _storeContext.Users.FirstOrDefaultAsync(u => u.Email == model.Email);
if (user == null)
{
user = new User { Email = model.Email, Password = model.Password, Adress = model.Adress, Phone = model.Phone, Name = model.Name };
if (user != null)
{
_storeContext.Users.Add(user);
await _storeContext.SaveChangesAsync();
await Authenticate(user);
}
else
{
ModelState.AddModelError("", "Некорректные логин и(или) пароль");
}
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", "Некорректные логин и(или) пароль");
}
}
return View(model);
}
[HttpGet]
public IActionResult Login()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LogInModel model)
{
if (ModelState.IsValid)
{
User user = await _storeContext.Users
.FirstOrDefaultAsync(u => u.Email == model.Email && u.Password == model.Password);
if (user != null)
{
await Authenticate(user);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", "Некорректные логин и(или) пароль");
}
}
return View(model);
}
private async Task Authenticate(User user)
{
var claims = new List<Claim>
{
new Claim(ClaimsIdentity.DefaultNameClaimType, user.Email),
new Claim(ClaimsIdentity.DefaultRoleClaimType, user.Role)
};
ClaimsIdentity id = new ClaimsIdentity(claims, "ApplicationCookie", ClaimsIdentity.DefaultNameClaimType,
ClaimsIdentity.DefaultRoleClaimType);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(id));
}
}
浏览量指数
@{
ViewData["Title"] = "Home Page";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
@if (User.Identity.IsAuthenticated)
{
<p>@User.Identity.IsAuthenticated</p>
<p>@User.Identity.AuthenticationType</p>
<p>@User.Identity.Name</p>
<p>admin - @User.IsInRole("Admin")</p>
}
else
{
<a class="register" asp-area="" asp-controller="Account" asp-action="Register" style="color: black">Регистрация</a>
<a class="login" asp-area="" asp-controller="Account" asp-action="LogIn" style="color: black">Вход</a>
}
@if (User.Identity.IsAuthenticated && User.IsInRole("Admin"))
{
<a style="color: green">admin</a>
}
else if (User.Identity.IsAuthenticated && User.IsInRole("User"))
{
<a style="color: red">user</a>
}
</div>
如果您在 HomeController 中注册
public IActionResult Index()
{
string role = User.FindFirst(x => x.Type == ClaimsIdentity.DefaultRoleClaimType).Value;
return Content($"ваша роль: {role}");
//return View();
}
然后他输出角色
但是他不去User.IsInRole("Admin")
我试图找到解决问题的方法,但没有找到