Khoá học web cho nhà máy, bài 7: xác thực JWT và phân quyền theo vai trò

Băm mật khẩu, đăng nhập cấp JWT, bảo vệ API bằng vai trò (Admin, Planner, Operator, Technician) trong ASP.NET Core, và dựng trang đăng nhập, route được bảo vệ, menu theo quyền trong React.

· 9 phút đọc#khoá học#JWT#xác thực#phân quyền#ASP.NET Core#React

Ứng dụng nhà máy chứa dữ liệu sản xuất, tồn kho, lịch sử bảo trì, và có thể ra lệnh (đổi trạng thái, trừ kho). Không thể để ai biết địa chỉ cũng gọi được. Bài này thêm hai lớp:

  • Xác thực (authentication): bạn là ai?
  • Phân quyền (authorization): bạn được làm gì?

1. Bốn vai trò của Factory

Vai trò Được làm
Admin Mọi thứ, quản lý người dùng
Planner Lập lệnh sản xuất, định mức, mua vật tư
Operator Ghi sản lượng, dừng máy, tạo yêu cầu bảo trì
Technician Xử lý lệnh bảo trì, dùng phụ tùng

Mọi người dùng đã đăng nhập đều xem được; việc ghi bị giới hạn theo vai trò. Khoá vai trò trong cơ sở dữ liệu (CHECK ở bài 4) khớp với đây.

2. Băm mật khẩu: không bao giờ lưu mật khẩu thật

Mật khẩu phải được băm một chiều có muối (salt) bằng thuật toán chậm chuyên dụng. ASP.NET Core có sẵn PasswordHasher<T> (PBKDF2, có muối, có số vòng lặp):

using Microsoft.AspNetCore.Identity;

var hasher = new PasswordHasher<object>();
string hash = hasher.HashPassword(null!, "MatKhauCuaBan");
var ok = hasher.VerifyHashedPassword(null!, hash, "MatKhauCuaBan")
         != PasswordVerificationResult.Failed;

Quy tắc: không tự viết thuật toán băm, không dùng MD5/SHA1 thuần, không ghi mật khẩu vào nhật ký, không gửi mật khẩu ngược lại cho người dùng.

3. Thực thể người dùng

Data/Entities/User.cs:

namespace Factory.Api.Data.Entities;

public class User
{
    public int Id { get; set; }
    public string Username { get; set; } = "";
    public string PasswordHash { get; set; } = "";
    public string FullName { get; set; } = "";
    public string Role { get; set; } = "Operator";
    public bool IsActive { get; set; } = true;
}

Trong FactoryDbContext thêm public DbSet<User> Users => Set<User>(); và ánh xạ:

b.Entity<User>(e =>
{
    e.ToTable("Users", "core");
    e.HasIndex(x => x.Username).IsUnique();
});

4. Cấu hình JWT

JWT (JSON Web Token) là một chuỗi đã ký, chứa thông tin người dùng (tên, vai trò, hạn). Máy chủ cấp khi đăng nhập; trình duyệt gửi kèm mỗi yêu cầu trong header Authorization: Bearer <token>. Máy chủ chỉ cần kiểm tra chữ ký, không phải tra cơ sở dữ liệu mỗi lần.

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
dotnet user-secrets set "Jwt:Key" "<chuoi-ngau-nhien-it-nhat-32-byte>"
dotnet user-secrets set "Seed:AdminPassword" "<mat-khau-admin-ban-dau>"

appsettings.json (phần không bí mật):

{
  "Jwt": { "Issuer": "factory-api", "Audience": "factory-web", "ExpireMinutes": 480 }
}

Auth/TokenService.cs:

using System.Security.Claims;
using System.Text;
using Factory.Api.Data.Entities;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;

namespace Factory.Api.Auth;

public class TokenService(IConfiguration cfg)
{
    public (string Token, DateTime ExpiresAt) Create(User u)
    {
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(cfg["Jwt:Key"]!));
        var expires = DateTime.UtcNow.AddMinutes(cfg.GetValue("Jwt:ExpireMinutes", 480));

        var descriptor = new SecurityTokenDescriptor
        {
            Issuer = cfg["Jwt:Issuer"],
            Audience = cfg["Jwt:Audience"],
            Expires = expires,
            Subject = new ClaimsIdentity(new[]
            {
                new Claim("sub", u.Id.ToString()),
                new Claim("name", u.FullName),
                new Claim("role", u.Role),
            }),
            SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256),
        };
        return (new JsonWebTokenHandler().CreateToken(descriptor), expires);
    }
}

Ta dùng tên claim ngắn sub, name, role, và sẽ nói cho ASP.NET Core biết cách đọc chúng (bước kế).

5. Đăng ký xác thực trong Program.cs

using System.Text;
using Factory.Api.Auth;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.IdentityModel.Tokens;

builder.Services.AddScoped<TokenService>();

builder.Services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(o =>
    {
        o.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,   ValidIssuer = builder.Configuration["Jwt:Issuer"],
            ValidateAudience = true, ValidAudience = builder.Configuration["Jwt:Audience"],
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]!)),
            NameClaimType = "name",
            RoleClaimType = "role",
            ClockSkew = TimeSpan.FromMinutes(1),
        };
    });

builder.Services.AddAuthorization(o =>
{
    // Mặc định mọi điểm cuối phải đăng nhập; điểm nào cho khách thì ghi [AllowAnonymous].
    o.FallbackPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();

    o.AddPolicy("CanPlan",  p => p.RequireRole("Admin", "Planner"));
    o.AddPolicy("CanOperate", p => p.RequireRole("Admin", "Planner", "Operator"));
    o.AddPolicy("CanMaintain", p => p.RequireRole("Admin", "Technician"));
});

// ... sau app.Build():
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();

Thứ tự quan trọng: UseAuthentication trước UseAuthorization, cả hai trước MapControllers.

FallbackPolicy là cách an toàn: nếu quên gắn [Authorize] ở một controller mới, điểm cuối vẫn bị khoá thay vì mở toang.

6. Điểm cuối đăng nhập

Controllers/AuthController.cs:

using Factory.Api.Auth;
using Factory.Api.Data;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace Factory.Api.Controllers;

[ApiController]
[Route("api/auth")]
public class AuthController(FactoryDbContext db, TokenService tokens) : ControllerBase
{
    public record LoginRequest(string Username, string Password);

    [AllowAnonymous]
    [HttpPost("login")]
    public async Task<IActionResult> Login(LoginRequest req)
    {
        var u = await db.Users.FirstOrDefaultAsync(x => x.Username == req.Username && x.IsActive);
        var hasher = new PasswordHasher<object>();

        // Cùng một thông báo cho "sai tên" và "sai mật khẩu" để không lộ tên nào có thật.
        if (u is null ||
            hasher.VerifyHashedPassword(null!, u.PasswordHash, req.Password) == PasswordVerificationResult.Failed)
            return Unauthorized(new { message = "Sai tên đăng nhập hoặc mật khẩu." });

        var (token, expires) = tokens.Create(u);
        return Ok(new { token, expiresAt = expires, user = new { u.Id, u.FullName, u.Role } });
    }

    [HttpGet("me")]
    public IActionResult Me() =>
        Ok(new { id = User.FindFirst("sub")?.Value, name = User.Identity?.Name, role = User.FindFirst("role")?.Value });
}

Tạo mật khẩu cho tài khoản admin lần đầu

Bài 4 để PasswordHash = 'CHANGE_ME'. Thêm đoạn khởi tạo vào Program.cs, sau Build() và trước Run():

using (var scope = app.Services.CreateScope())
{
    var db = scope.ServiceProvider.GetRequiredService<FactoryDbContext>();
    var admin = db.Users.FirstOrDefault(u => u.Username == "admin");
    var pwd = app.Configuration["Seed:AdminPassword"];
    if (admin is { PasswordHash: "CHANGE_ME" } && !string.IsNullOrEmpty(pwd))
    {
        admin.PasswordHash = new PasswordHasher<object>().HashPassword(null!, pwd);
        db.SaveChanges();
    }
}

Chạy lại API một lần rồi có thể xoá biến Seed:AdminPassword. Mật khẩu admin chỉ nằm trong user-secrets, không nằm trong mã hay Git.

7. Gắn phân quyền vào controller

Từ bài 6, AssetsController không có [Authorize], nhưng nhờ FallbackPolicy nó đã yêu cầu đăng nhập. Muốn ghi chỉ cho một số vai trò:

[HttpPost, Authorize(Policy = "CanPlan")]
public async Task<ActionResult<AssetDto>> Create(AssetInput input) { /* ... */ }

[HttpPut("{id:int}"), Authorize(Policy = "CanPlan")]
public async Task<IActionResult> Update(int id, AssetInput input) { /* ... */ }

[HttpDelete("{id:int}"), Authorize(Roles = "Admin")]
public async Task<IActionResult> Delete(int id) { /* ... */ }

Mã trả về: chưa đăng nhập hoặc token hết hạn là 401, đã đăng nhập nhưng không đủ quyền là 403.

Phân quyền ở máy chủ là bắt buộc. Việc giấu nút trong giao diện chỉ để dễ dùng, không phải bảo mật. Ai cũng gọi được API bằng Postman.

8. Phía React

Ngữ cảnh đăng nhập

src/auth/AuthContext.jsx:

import { createContext, useCallback, useContext, useMemo, useState } from "react";

const AuthContext = createContext(null);
const KEY = "factory.auth";

function load() {
  try {
    const a = JSON.parse(sessionStorage.getItem(KEY));
    return a && new Date(a.expiresAt) > new Date() ? a : null;
  } catch {
    return null;
  }
}

export function AuthProvider({ children }) {
  const [auth, setAuth] = useState(load);

  const login = useCallback(async (username, password) => {
    const res = await fetch("/api/auth/login", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ username, password }),
    });
    if (!res.ok) throw new Error((await res.json()).message ?? "Đăng nhập thất bại");
    const data = await res.json();
    sessionStorage.setItem(KEY, JSON.stringify(data));
    setAuth(data);
  }, []);

  const logout = useCallback(() => {
    sessionStorage.removeItem(KEY);
    setAuth(null);
  }, []);

  const value = useMemo(
    () => ({
      user: auth?.user ?? null,
      token: auth?.token ?? null,
      login,
      logout,
      hasRole: (...roles) => !!auth && roles.includes(auth.user.Role ?? auth.user.role),
    }),
    [auth, login, logout]
  );
  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}

export const useAuth = () => useContext(AuthContext);

Lưu ý: JSON do ASP.NET Core trả về dùng camelCase (user.role), nên hasRole đã chấp nhận cả hai kiểu. Ta dùng sessionStorage (mất khi đóng tab). Cách an toàn hơn trước tấn công XSS là cookie HttpOnly, đòi hỏi thêm cấu hình CSRF; nằm ngoài phạm vi bài này, nhưng cần biết khi làm sản phẩm thật.

api() gắn token và xử lý 401

Sửa hàm api ở bài 2:

export async function api(path, { method = "GET", body } = {}) {
  const raw = sessionStorage.getItem("factory.auth");
  const token = raw ? JSON.parse(raw).token : null;

  const res = await fetch(`/api${path}`, {
    method,
    headers: {
      ...(body ? { "Content-Type": "application/json" } : {}),
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
    },
    body: body ? JSON.stringify(body) : undefined,
  });

  if (res.status === 401) {
    sessionStorage.removeItem("factory.auth");
    window.location.assign("/login");
    throw new Error("Hết phiên đăng nhập");
  }
  if (!res.ok) {
    const text = await res.text();
    let message = text;
    try { message = JSON.parse(text).message ?? text; } catch { /* giữ nguyên */ }
    throw new Error(message || `Lỗi ${res.status}`);
  }
  return res.status === 204 ? null : res.json();
}

Route được bảo vệ và trang đăng nhập

import { Navigate, Outlet, useLocation } from "react-router-dom";
import { useAuth } from "./auth/AuthContext.jsx";

export function RequireAuth() {
  const { user } = useAuth();
  const location = useLocation();
  return user ? <Outlet /> : <Navigate to="/login" state={{ from: location }} replace />;
}
// pages/Login.jsx
import { useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { useAuth } from "../auth/AuthContext.jsx";

export default function Login() {
  const { login } = useAuth();
  const navigate = useNavigate();
  const from = useLocation().state?.from?.pathname ?? "/";
  const [u, setU] = useState("");
  const [p, setP] = useState("");
  const [error, setError] = useState("");
  const [busy, setBusy] = useState(false);

  async function submit(e) {
    e.preventDefault();
    setBusy(true);
    setError("");
    try {
      await login(u, p);
      navigate(from, { replace: true });
    } catch (err) {
      setError(err.message);
    } finally {
      setBusy(false);
    }
  }

  return (
    <form onSubmit={submit} className="login">
      <h2>Đăng nhập Factory</h2>
      <input value={u} onChange={(e) => setU(e.target.value)} placeholder="Tên đăng nhập" autoFocus />
      <input type="password" value={p} onChange={(e) => setP(e.target.value)} placeholder="Mật khẩu" />
      {error && <p role="alert">{error}</p>}
      <button disabled={busy || !u || !p}>{busy ? "Đang đăng nhập…" : "Đăng nhập"}</button>
    </form>
  );
}

Trong App.jsx, bọc ba phân hệ vào <Route element={<RequireAuth />}> và đặt <Route path="/login" element={<Login />} /> bên ngoài. Bọc toàn ứng dụng bằng <AuthProvider> trong main.jsx. Menu có thể ẩn mục theo vai trò: {hasRole("Admin","Planner") && <NavLink ...>}.

9. Danh sách kiểm tra bảo mật tối thiểu

  1. Mật khẩu được băm; khoá JWT dài, ngẫu nhiên và nằm ngoài Git.
  2. Mọi điểm cuối mặc định phải đăng nhập (FallbackPolicy).
  3. Phân quyền kiểm tra ở máy chủ, không chỉ ẩn nút.
  4. Chạy qua HTTPS khi triển khai; HTTP thường làm lộ token.
  5. Thời hạn token ngắn vừa phải (ví dụ một ca 8 giờ) và có cách đăng xuất.
  6. Giới hạn số lần đăng nhập sai (AddRateLimiter hoặc khoá tạm), để chống dò mật khẩu.
  7. Không ghi mật khẩu hoặc token vào nhật ký.

Bài tập

  1. Thêm UsersController (chỉ Admin) để tạo người dùng, đổi vai trò, vô hiệu hoá tài khoản, đổi mật khẩu (băm khi lưu).
  2. Thêm điểm cuối POST /api/auth/change-password cho người dùng tự đổi mật khẩu, yêu cầu nhập mật khẩu cũ.
  3. Viết một thành phần <Can roles={["Admin","Planner"]}> bọc nút "Thêm" để chỉ hiện khi đủ quyền.
  4. Gọi DELETE /api/assets/1 bằng token của Operator và xác nhận nhận 403, không phải 401.

Tóm tắt

  • Xác thực chứng minh danh tính (mật khẩu băm + JWT); phân quyền giới hạn hành động (vai trò, chính sách).
  • Dùng FallbackPolicy để mặc định khoá, [AllowAnonymous] chỉ cho đăng nhập.
  • React giữ token, gắn vào mọi yêu cầu, đẩy về trang đăng nhập khi gặp 401.
  • Giấu nút chỉ là tiện lợi; bảo mật thật nằm ở máy chủ.
  • Bài 8 làm giao diện dùng API thật: tải dữ liệu, form, bảng có phân trang.