Authentication (xác thực) trong ASP.NET Core MVC sử dụng Cookie Authentication
Có 2 cách:
Tạo project với Authentication type = Individual accounts (có sẵn phần Authentication, dùng Identity Code First)
Tạo project với Authentication type = None (tự định nghĩa authentication & authorize)
Tự tạo Project dạng MVC và chọn Authentication type = Individual accounts
Hiệu chỉnh chuỗi kết nối cho đúng server, database nhà bạn
Mở Package Manager Console rồi gõ lệnh Update-Database
Thử chạy ứng dụng: Register --> Confirm Email --> Login --> Logout
Thử change layout Login, Logout rùi chạy
Chuột phải vô Project ==> Add ==> New Scaffolded Item ==> Identity ==> ở màn hình Add Identity chọn layout muốn thay đổi
Thực hiện chỉnh layout
Thử thêm Entity Model mới vào trong database.
Tạo mới Entity Model, ví dụ Product
Khai báo thêm vào ApplicationDbContext
public DbSet<Product> Products {get; set;}
Tạo mới Migration:
Add-Migration NewEntity
Cập nhật database
Update-Database
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.