Hiểu về Xác thực Cookie trong ASP.NET Core

Trong các giải pháp xác thực web, chúng ta có thể phân loại thành hai nhóm chính: các phương thức xác thực theo tiêu chuẩn HTTP như "Basic", "Digest", "Bearer", và các phương thức không chuẩn như xác thực Form, xác thực cookie. Bài viết này sẽ tập trung vào việc triển khai xác thực cookie.

  1. Tạo một ứng dụng ASP.NET Core với MVC, trong ví dụ này chúng ta sử dụng .NET 5. (Toàn bộ mã nguồn có sẵn ở cuối bài)

  2. Cấu hình xác thực trong Startup

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(options =>
    {
        options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    }).AddCookie(options =>
    {
        // Cấu hình chi tiết cho xác thực cookie
        options.Cookie.Name = "UserAuthCookie"; // Tên cookie
        options.LoginPath = "/Account/Login"; // Đường dẫn đăng nhập
        options.Cookie.HttpOnly = true; // Quyền truy cập cookie
    });
    services.AddControllersWithViews();
}

// Phương thức này được gọi bởi runtime. Sử dụng để cấu hình pipeline HTTP request
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // Xác thực người dùng, chú ý thứ tự, phải đặt trước UseAuthorization
    app.UseAuthentication();

    // Kiểm tra quyền truy cập
    app.UseAuthorization();      

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}
  1. Thêm UserController.cs với logic xác thực
public class UserController : Controller
{
    private readonly IUserRepository _userRepository;
    private readonly IHttpContextAccessor _httpContextAccessor;
    
    public UserController(IUserRepository userRepository, IHttpContextAccessor httpContextAccessor)
    {
        _userRepository = userRepository;
        _httpContextAccessor = httpContextAccessor;
    }
    
    // Trang chủ người dùng
    public IActionResult Index()
    {
        var isAuthenticated = _httpContextAccessor.HttpContext?.User?.Identity?.IsAuthenticated ?? false;
        
        if (isAuthenticated)
        {
            var userInfo = new StringBuilder();
            userInfo.Append($"Người dùng hiện tại: {_httpContextAccessor.HttpContext.User.Identity.Name}<br/>");
            userInfo.Append($"Loại xác thực: {_httpContextAccessor.HttpContext.User.Identity.AuthenticationType}<br/>");
            
            foreach (var claim in _httpContextAccessor.HttpContext.User.Claims)
            {
                userInfo.Append($"{claim.Type}-{claim.Value}<br/>");
            }
            
            ViewBag.UserInfo = userInfo.ToString();
        }
        
        ViewBag.IsAuthenticated = isAuthenticated;
        return View();
    }
    
    // Trang đăng nhập
    public IActionResult Login(string errorMessage)
    {
        ViewBag.ErrorMessage = errorMessage;
        return View();
    }
    
    // Xử lý đăng nhập
    [HttpPost]
    public IActionResult Login(string username, string password)
    {
        var user = _userRepository.Authenticate(username, password);
        
        if (user == null)
        {
            return RedirectToAction("Login", new { errorMessage = "Tên người dùng hoặc mật khẩu không chính xác" });
        }
        else
        {
            var claimsIdentity = new ClaimsIdentity("CookieAuth");
            claimsIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()));
            claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, user.Username));
            claimsIdentity.AddClaim(new Claim(ClaimTypes.Email, user.Email));
            claimsIdentity.AddClaim(new Claim(ClaimTypes.MobilePhone, user.Phone));
            claimsIdentity.AddClaim(new Claim(ClaimTypes.DateOfBirth, user.BirthDate.ToString()));

            var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
            HttpContext.SignInAsync(claimsPrincipal);
            return RedirectToAction("Index");
        }
    }
    
    // Đăng xuất
    public IActionResult Logout()
    {
        HttpContext.SignOutAsync();
        return RedirectToAction("Index", "Home");
    }
}
  1. Áp dụng xác thực: Sử dụng thuộc tính [Authorize] để bảo vệ các action
// Bảo vệ action bằng xác thực
[Authorize]
public IActionResult PrivateData()
{
    return View();
}
  1. Mã nguồn hoàn chỉnh: https://github.com/example/aspnetcore-cookie-auth

Nguồn gốc: https://www.cnblogs.com/RainingNight/p/cookie-authentication-in-asp-net-core.html

Thẻ: ASP.NET Core Cookie Authentication Identity Claims authorization

Đăng vào ngày 16 tháng 7 lúc 11:20