Để thiết lập cơ chế xác thực dựa trên Cookie trong ứng dụng ASP.NET Core, chúng ta cần cấu hình các dịch vụ và đường ống xử lý request. Dưới đây là các bước chi tiết để triển khai.
1. Cấu hình dịch vụ và đường ống HTTP
Trong lớp Startup, hãy đăng ký dịch vụ xác thực và thiết lập các tùy chọn Cookie. Đồng thời, đảm bảo rằng middleware xác thực được thêm vào đúng vị trí trong đường ống request.
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace CookieAuthDemo
{
public class Startup
{
public Startup(IConfiguration config)
{
Configuration = config;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/Auth/Login";
options.AccessDeniedPath = "/Auth/AccessDenied";
});
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();
// Middleware xác thực phải được đặt trước middleware ủy quyền
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
2. Bảo vệ tài nguyên bằng thuộc tính ủy quyền
Để giới hạn quyền truy cập vào các controller hoặc action cụ thể, hãy sử dụng thuộc tính [Authorize]. Bạn có thể chỉ định vai trò yêu cầu để truy cập.
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace CookieAuthDemo.Controllers
{
[Authorize(Roles = "Manager")]
public class DashboardController : Controller
{
// Chỉ những người dùng có vai trò "Manager" mới có thể truy cập
public IActionResult Index()
{
return View();
}
}
}
3. Tạo phiếu xác thực (Claims) khi đăng nhập
Khi người dùng cung cấp thông tin đăng nhập hợp lệ, hệ thống sẽ tạo một danh sách các claim, đóng gói chúng vào ClaimsIdentity và đăng nhập người dùng vào hệ thống.
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
namespace CookieAuthDemo.Controllers
{
public class AuthController : Controller
{
[HttpPost]
public async Task<IActionResult> Login(string username, string password)
{
// Thực hiện kiểm tra thông tin đăng nhập với cơ sở dữ liệu ở đây
if (username == "admin" && password == "password123")
{
var userClaims = new List<Claim>
{
new Claim(ClaimTypes.Name, username),
new Claim(ClaimTypes.NameIdentifier, "1001"),
new Claim(ClaimTypes.Role, "Manager")
};
var identity = new ClaimsIdentity(userClaims, CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
principal);
return RedirectToAction("Index", "Home");
}
return View();
}
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return RedirectToAction("Login");
}
}
}
4. Truy xuất thông tin người dùng hiện tại
Trong các controller hoặc view, bạn có thể dễ dàng đọc các claim của người dùng đã đăng nhập thông qua đối tượng User.
using System.Security.Claims;
using Microsoft.AspNetCore.Mvc;
namespace CookieAuthDemo.Controllers
{
public class ProfileController : Controller
{
public IActionResult Index()
{
var currentUserName = User.FindFirst(ClaimTypes.Name)?.Value;
var userRole = User.FindFirst(ClaimTypes.Role)?.Value;
ViewBag.DisplayName = currentUserName;
ViewBag.UserRole = userRole;
return View();
}
}
}