Authentication (xác thực) trong ASP.NET Core MVC sử dụng Cookie Authentication
Bước 1: Cấu hình dịch vụ Authentication trong Program.cs
builder.Services.AddAuthentication("MyCookieAuth")
.AddCookie("MyCookieAuth", options =>
{
options.Cookie.Name = "MyCookieAuth";
options.LoginPath = "/Account/Login";
options.AccessDeniedPath = "/Account/AccessDenied";
});
builder.Services.AddAuthorization();
thêm 2 lệnh sau ở phần app:
app.UseAuthentication();
app.UseAuthorization();
Bước 2: Tạo Controller xử lý đăng nhập (AccountController.cs)
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
public class AccountController : Controller
{
public IActionResult Login()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Login(string username, string password)
{
// Ví dụ kiểm tra đơn giản, bạn có thể thay bằng truy vấn DB
if (username == "admin" && password == "123")
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, username),
new Claim("Role", "Admin")
};
var identity = new ClaimsIdentity(claims, "MyCookieAuth");
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync("MyCookieAuth", principal);
return RedirectToAction("Index", "Home");
}
ViewBag.Error = "Sai thông tin đăng nhập!";
return View();
}
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync("MyCookieAuth");
return RedirectToAction("Login");
}
public IActionResult AccessDenied()
{
return View("AccessDenied");
}
}
Bước 3: Tạo view Login (Views/Account/Login.cshtml)
<form asp-action="Login" method="post">
<label>Username: </label>
<input name="username" />
<br />
<label>Password: </label>
<input name="password" type="password" />
<br />
<button type="submit">Login</button>
</form>
@if (ViewBag.Error != null)
{
<div style="color:red">@ViewBag.Error</div>
}
Bước 4: Bảo vệ các Controller hoặc Action
Thêm thuộc tính [Authorize] trước Controller hoặc Action. Ví dụ:
using Microsoft.AspNetCore.Authorization;
[Authorize]
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}
Bổ sung danh sách các Role từ database ở mục khai báo Claim sau khi kiểm tra đăng nhập thành công.
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, username),
new Claim("Role", "Admin")
};
Sử dụng [Authorize(Roles = "TênVaiTrò")] để phân quyền
Ví dụ:
[Authorize(Roles = "Admin")]
public class AdminController : Controller
{
public IActionResult Index()
{
return View();
}
}
Hoặc bạn có thể phân quyền riêng cho một action:
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[Authorize(Roles = "Admin")]
public IActionResult SecretForAdmins()
{
return View("Secret");
}
}
Hiển thị tên Role ở _Layout.cshtml hoặc bất kỳ View nào:
@if (User.Identity.IsAuthenticated)
{
<p>Hello, @User.Identity.Name!</p>
@if (User.IsInRole("Admin"))
{
<p>You are an Admin!</p>
}
}
Bạn có thể có nhiều role, ví dụ: "Admin,Editor", phân cách bởi dấu phẩy.
Cấu hình DbContext và Identity
Tạo class ApplicationDbContext.cs:
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
public class ApplicationDbContext : IdentityDbContext<IdentityUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options) { }
}
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddDefaultIdentity<IdentityUser>(options =>
{
options.SignIn.RequireConfirmedAccount = false;
})
.AddRoles<IdentityRole>() // nếu dùng Role
.AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.AddControllersWithViews();
Các bước khác thực hiện bình thường.