ASP.NET Identity — Part 1

Minh Tâm
4 min readJan 23, 2023

--

Authentication và Authorization luôn là chủ đề mà mình muốn tìm hiểu từ lâu. Trước kia mình thường dựa trên thư viện có sẵn, nhưng nay thử tìm hiểu xem cơ chế hoạt động của các thư viện ra sao.

Ngoài ra, một phần là mình thất vọng về việc IdentityServer đã chuyển đổi lience từ OpenSource sang Commercial. Trong tương lai, có thể mình sẽ tìm hiểu thêm một vài thư viện khác để bổ sung cho phần Membership trong ASP.NET Core

Hiện tại có một số thư viện mà mình quan tâm: Auth0, Okta, Keycloak, Azure Active Directory B2C.

Tạo Project ASP.NET Core

Tạo Project ASP.NET Core (Model-View-Controller). Ở option ASP.NET Identity, bạn chọn No Authentication.

Để thêm Authentication và Authorization, bạn cần qua các bước sau:

  • Thêm thuộc tính [Authorize], chỉ thị này áp dụng được cho Controller, Action của Controller, được dùng để xác định ai được quyền truy cập Controller, Action của Controller.
  • Setup Authentication và Authorization trong Startup của application
  • Tạo trang Login page và xử lý data khi người dùng đăng nhập

ASP.NET Identity là gì?

ASP.NET Identity is Microsoft’s user management library for ASP.NET. It includes functionality such as password hashing, password validation, user storage, and claims management. It usually also comes with some basic authentication, bringing its own cookies and multi-factor authentication to the party.

ASP.NET Core Identity là một thành phần (built-in) của ASP.NET Core, nó cung cấp cho bạn các tính năng đầy đủ và đa dạng về authentication.

Có 2 service quan trọng trong ASP.NET Identity là UserManager Sign in Manager

  • UserManager: Create, Update, Delete, find…. Users
  • Sign in Manager: xử lý khi user đăng nhập.

Trong bài này, mình sẽ xử dụng Sign in Manager trước. Đây là service rất quan trọng để xử lý đăng nhập bằng cookie.

Setup Authentication và Authorization

Đầu tiên, chúng ta cần hiểu nghĩa về 2 từ Authentication và Authorization.

Authentication nghĩa là định danh, xác định xem bạn là ai. Trả lời cho câu hỏi: Who are you?

Authorization nghĩa là phân quyền. Sau khi xác thực bạn là ai, hệ thống sẽ xác định bạn có quyền truy cập vào tài nguyên hệ thống vào thời điểm hiện tại không. Trả lời cho câu hỏi: What can you do? What can you access?

Để thêm phân quyền trong ASP.NET Core, bạn thêm thuộc tính Authorize trước Controller hoặc Action mà bạn kiểm tra phân quyền.

Giả sử bạn có 3 action như sau:

  • Index: Đây là homepage của application
  • Secret: Chỉ cho phép người dùng đã xác thực mới được xem page.
  • Authenticate: Page này dùng để đăng nhập
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;

public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}

public IActionResult Index()
{
return View();
}

[Authorize]
public IActionResult Secret()
{
return View();
}

public IActionResult Authenticate()
{
return RedirectToAction("Index");
}
}

Khi bạn chưa setup gì cả, bạn sẽ không vào được trang /Home/Secret

Thứ tự Routing, Authentication, và Authorization>

Vậy thứ tự của 3 thành phần Routing, Authentication, và Authorization như thế nào?

VD: Bạn cần đến Bank để rút tiền, đầu tiên bạn cần xác định đường đi để đi tới, sau đó dùng thẻ căn cước để xác định bạn là ai, sau đó dựa vào quyền truy cập, hệ thống sẽ cho phép bạn sử dụng Bank

=>Sẽ là Routing, Authentication, và Authorization.

app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

Bạn cần thêm thuộc tính [Authorize] cho Controllers hoặc Actions cần kiểm tra phân quyền VD:

[Authorize]
public IActionResult Index()
{
return View();
}

Setup Authentication

Ở đoạn trước mình có dùng câu lệnh:

app.UseAuthentication();

Vậy làm sao thiết lập Authentication. Các bạn chú ý 2 nhóm hàm: AddAuthentication và AddCookie, AddJwtBearer

AddAuthentication: chỉ ra scheme được sử dụng. Có thể setup 1 hoặc nhiều scheme

AddCookie, AddJwtBearer: khai báo cookie, JWT, và phụ thuộc vào scheme đã khai báo ở method AddAuthentication

VD:

builder.Services.AddAuthentication("CookieAuth")
.AddCookie("CookieAuth", config =>
{
config.Cookie.Name = "NgocTho";
config.LoginPath = "/account/login";
});

CookieName: tên cookie được lưu ở máy client

LoginPath: Chuyển đến trang login nếu người dùng chưa được xác thực

ChallengeAsync: một request và một response. Mục tiêu là xác thực người dùng là ai.

Khi người dùng vào trang /Home/Secret mà chưa đăng nhập, hệ thống sẽ trả về trang /Account/Login

Setup Authorization

Authorization là quá trình xác định xem một người dùng có quyền truy cập một URL / tài nguyên cụ thể hoặc để thực hiện một số hành động hay không,

Để làm được điều đó, bạn cần setup principle, claim identity và claim cho user.

Để dễ hình dung, bạn tưởng tượng Principal là 1 ví, trong ví chứa nhiều thông tin như CCCD, Giấy phép lái xe, … (claim identity). Ở mỗi claim identity, ví dụ như Giấy phép lái xe, sẽ chứa tập hợp nhiều identity như name, birthday, phone number, home address.

VD:

public async Task<IActionResult> Authenticate()
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, "AnAnh"),
new Claim(ClaimTypes.Email, "ananh@test.com")
};
var drivingClaims = new List<Claim>
{
new Claim(ClaimTypes.Name, "AnAnh"),
new Claim("DrivingLicense", "B+")
};
var userIdentity = new ClaimsIdentity(claims, _authenticateType);
var licenseIdentity = new ClaimsIdentity(drivingClaims, CookieAuthenticationDefaults.AuthenticationScheme);
var userPrincipal = new ClaimsPrincipal(new[] {userIdentity, licenseIdentity});
await HttpContext.SignInAsync(userPrincipal);
return RedirectToAction("Index");
}

Claim chứa thông tin về user, role, hoặc permission.

Để group thông tin của Claim, bạn sử dụng ClaimIdentity

public class ClaimsIdentity {
public string Name { get; }
public IEnumerable<Claim> Claims { get; }
public string AuthenticationType { get; }
public bool IsAuthenticated { get; }
// some properties have been omitted.
}

uthenticationType property lưu trữ phương thức đăng nhập, vd như “Bearer”, “Basic”, và IsAuthenticated = true khi AuthenticationType có giá trị.

Tham khảo

https://eddieabbondanz.io/post/aspnet/claims-based-authentication-claims-identities-principals/

https://www.tektutorialshub.com/asp-net-core/asp-net-core-identity-tutorial/#aspnet-core-identity

Hi vọng với bài viết này, các bạn sẽ nắm thêm về Security trong ASP.NET Core

Nhatkyhoctap’s blog

--

--