[Authorize(Roles = "admin")]
public IActionResult Index()
{
return View();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
options.LoginPath = new PathString("/Auth/Login");
options.AccessDeniedPath = new PathString("/Auth/AccessDen");
});
services.AddSingleton<IConfiguration>(Configuration);
services.AddDistributedMemoryCache();
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSession(opts =>
{
opts.Cookie.IsEssential = true; // make the session cookie Essential
});
services.AddControllersWithViews();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCookiePolicy();
app.UseSession();
app.UseDeveloperExceptionPage();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Auth}/{action=Login}/{id?}");
});
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(string iin,string pas)
if (iin != null && pas!= null)
{
Users users = await reposUsers.FindUser(iin, pas); //Использую PostgreSQL+Dapper
if (users != null)
{
await Authenticate(iin, users.role);
return RedirectToAction("Index", "Admin");
}
}
}
private async Task Authenticate(string iin,string role)
{
// создаем один claim
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, iin),
new Claim(ClaimTypes.Role, role),
};
// создаем объект ClaimsIdentity
ClaimsIdentity id = new ClaimsIdentity(claims, "ApplicationCookie", ClaimsIdentity.DefaultNameClaimType,
ClaimsIdentity.DefaultRoleClaimType);
// установка аутентификационных куки
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(id));
}