[CLAUDE] Phase5.1: Security headers + account lockout + Users management

Security hardening:
- Api/Middleware/SecurityHeadersMiddleware MOI: remove server fingerprint (Server, X-Powered-By, ...), add X-Content-Type-Options:nosniff, X-Frame-Options:DENY, Referrer-Policy:strict-origin-when-cross-origin, Permissions-Policy (disable geolocation/mic/cam/payment), X-Permitted-Cross-Domain-Policies:none, CSP (default-src 'self' + img data: + style inline for Tailwind + frame-ancestors 'none'). Skip CSP tren /swagger (dung inline script).
- Program.cs wire UseMiddleware SecurityHeadersMiddleware first in pipeline
- Infrastructure/DependencyInjection Identity options:
  - Password.RequiredLength config-driven (Identity:Password:RequiredLength, default 8 dev, override 12+ prod)
  - Lockout: DefaultLockoutTimeSpan (15min), MaxFailedAccessAttempts (5), AllowedForNewUsers=true — all config-driven
- LoginCommandHandler: IsLockedOutAsync check truoc → throw voi deadline message, AccessFailedAsync khi sai password, ResetAccessFailedCountAsync khi login thanh cong

Users management:
- Application/Users/UserFeatures.cs: 8 CQRS (ListUsersQuery paging+search, GetUserQuery, CreateUserCommand + Validator, UpdateUserCommand voi self-disable protection, AssignRolesCommand voi self-demote protection (khong tu go Admin), ResetPasswordCommand (invalidate refresh token + unlock), UnlockUserCommand)
- UserDto: Id, Email, FullName, IsActive, IsLocked (computed tu LockoutEnd), CreatedAt, Roles
- Api/Controllers/UsersController: 7 endpoint (Users.Read/Create/Update policies):
  - GET / (list paged), GET /{id}, POST /, PUT /{id}, PUT /{id}/roles, POST /{id}/reset-password, POST /{id}/unlock
- using alias ValidationException = Application.Common.Exceptions.ValidationException (fix ambiguity voi FluentValidation)

Frontend fe-admin:
- types/users.ts MOI: User type + AVAILABLE_ROLES 12 role (match BE AppRoles.cs) + RoleLabel Vietnamese
- pages/system/UsersPage.tsx MOI:
  - DataTable columns: Email (mono), FullName, Roles (badge chips voi Vietnamese label), IsActive (CheckCircle/XCircle), IsLocked (KeyRound red), CreatedAt
  - Actions per row (PermissionGuard Users.Update wrap): Gan role (Shield icon → Dialog grid 12 checkbox), Reset password (KeyRound → Dialog voi warning user se bi logout), Unlock (Unlock icon, chi hien khi isLocked), Toggle active (XCircle/CheckCircle)
  - Create user dialog: email + fullName + password (min 8) + grid 12 role checkbox
- Route /system/users vao App.tsx

E2E verified:
- Security headers present tren moi response (check qua curl -I)
- POST /api/users voi roles: [Drafter] → 201 + id
- GET /api/users → paged voi 2 user (admin + new test.drafter)
- TS check fe-admin → pass
- dotnet build → 0 errors

Docs:
- docs/STATUS.md: Phase 5.1 xong, cumulative BE 3700 LOC, 42 endpoints, 17 FE pages
- docs/HANDOFF.md: phase table update row Phase 5.1, last updated timestamp
- docs/changelog/migration-todos.md: tick 6 items Phase 5.1 + 4 items remaining (IDOR, deps scan, admin warning, Roles CRUD)
- docs/changelog/sessions/2026-04-21-1630-phase5-1-security-users.md: session log

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
EOF
This commit is contained in:
pqhuy1987
2026-04-21 13:06:46 +07:00
parent 46a2cab788
commit 11e61c9c39
13 changed files with 909 additions and 33 deletions

View File

@ -19,32 +19,39 @@ public class LoginCommandValidator : AbstractValidator<LoginCommand>
}
}
public class LoginCommandHandler : IRequestHandler<LoginCommand, AuthResponseDto>
public class LoginCommandHandler(
UserManager<User> userManager,
IJwtTokenService jwtTokenService) : IRequestHandler<LoginCommand, AuthResponseDto>
{
private readonly UserManager<User> _userManager;
private readonly IJwtTokenService _jwtTokenService;
public LoginCommandHandler(UserManager<User> userManager, IJwtTokenService jwtTokenService)
{
_userManager = userManager;
_jwtTokenService = jwtTokenService;
}
public async Task<AuthResponseDto> Handle(LoginCommand request, CancellationToken cancellationToken)
{
var user = await _userManager.FindByEmailAsync(request.Email);
var user = await userManager.FindByEmailAsync(request.Email);
if (user is null || !user.IsActive)
throw new UnauthorizedException("Email hoặc mật khẩu không đúng.");
if (!await _userManager.CheckPasswordAsync(user, request.Password))
throw new UnauthorizedException("Email hoặc mật khẩu không đúng.");
// Check lockout trước
if (await userManager.IsLockedOutAsync(user))
{
var until = user.LockoutEnd;
throw new UnauthorizedException($"Tài khoản bị khóa do nhập sai nhiều lần. Thử lại sau {until:HH:mm}.");
}
var roles = await _userManager.GetRolesAsync(user);
var tokens = await _jwtTokenService.GenerateTokensAsync(user, roles);
if (!await userManager.CheckPasswordAsync(user, request.Password))
{
// Tăng AccessFailedCount + auto lock khi đủ ngưỡng
await userManager.AccessFailedAsync(user);
throw new UnauthorizedException("Email hoặc mật khẩu không đúng.");
}
// Success → reset failed count
await userManager.ResetAccessFailedCountAsync(user);
var roles = await userManager.GetRolesAsync(user);
var tokens = await jwtTokenService.GenerateTokensAsync(user, roles);
user.RefreshToken = tokens.RefreshToken;
user.RefreshTokenExpiresAt = tokens.RefreshTokenExpiresAt;
await _userManager.UpdateAsync(user);
await userManager.UpdateAsync(user);
return new AuthResponseDto(
tokens.AccessToken,

View File

@ -0,0 +1,248 @@
using FluentValidation;
using MediatR;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using SolutionErp.Application.Common.Exceptions;
using SolutionErp.Application.Common.Interfaces;
using SolutionErp.Application.Common.Models;
using SolutionErp.Domain.Identity;
using ValidationException = SolutionErp.Application.Common.Exceptions.ValidationException;
namespace SolutionErp.Application.Users;
public record UserDto(
Guid Id,
string Email,
string FullName,
bool IsActive,
bool IsLocked,
DateTime CreatedAt,
List<string> Roles);
// ========== LIST ==========
public record ListUsersQuery : PagedRequest, IRequest<PagedResult<UserDto>>;
public class ListUsersQueryHandler(UserManager<User> userManager, IDateTime dateTime)
: IRequestHandler<ListUsersQuery, PagedResult<UserDto>>
{
public async Task<PagedResult<UserDto>> Handle(ListUsersQuery request, CancellationToken ct)
{
var query = userManager.Users.AsNoTracking();
if (!string.IsNullOrWhiteSpace(request.Search))
{
var s = request.Search.Trim();
query = query.Where(u => u.Email!.Contains(s) || u.FullName.Contains(s));
}
query = request.SortDesc
? query.OrderByDescending(u => u.CreatedAt)
: query.OrderBy(u => u.CreatedAt);
var total = await query.CountAsync(ct);
var users = await query
.Skip((request.Page - 1) * request.PageSize)
.Take(request.PageSize)
.ToListAsync(ct);
var items = new List<UserDto>(users.Count);
var now = dateTime.UtcNow;
foreach (var u in users)
{
var roles = await userManager.GetRolesAsync(u);
var isLocked = u.LockoutEnd.HasValue && u.LockoutEnd.Value.UtcDateTime > now;
items.Add(new UserDto(u.Id, u.Email!, u.FullName, u.IsActive, isLocked, u.CreatedAt, roles.ToList()));
}
return new PagedResult<UserDto>(items, total, request.Page, request.PageSize);
}
}
// ========== GET ==========
public record GetUserQuery(Guid Id) : IRequest<UserDto>;
public class GetUserQueryHandler(UserManager<User> userManager, IDateTime dateTime)
: IRequestHandler<GetUserQuery, UserDto>
{
public async Task<UserDto> Handle(GetUserQuery request, CancellationToken ct)
{
var u = await userManager.FindByIdAsync(request.Id.ToString())
?? throw new NotFoundException("User", request.Id);
var roles = await userManager.GetRolesAsync(u);
var isLocked = u.LockoutEnd.HasValue && u.LockoutEnd.Value.UtcDateTime > dateTime.UtcNow;
return new UserDto(u.Id, u.Email!, u.FullName, u.IsActive, isLocked, u.CreatedAt, roles.ToList());
}
}
// ========== CREATE ==========
public record CreateUserCommand(string Email, string FullName, string Password, List<string> Roles)
: IRequest<Guid>;
public class CreateUserCommandValidator : AbstractValidator<CreateUserCommand>
{
public CreateUserCommandValidator()
{
RuleFor(x => x.Email).NotEmpty().EmailAddress().MaximumLength(100);
RuleFor(x => x.FullName).NotEmpty().MaximumLength(200);
RuleFor(x => x.Password).NotEmpty().MinimumLength(8);
RuleFor(x => x.Roles).NotNull();
}
}
public class CreateUserCommandHandler(
UserManager<User> userManager,
RoleManager<Role> roleManager,
IDateTime dateTime) : IRequestHandler<CreateUserCommand, Guid>
{
public async Task<Guid> Handle(CreateUserCommand request, CancellationToken ct)
{
if (await userManager.FindByEmailAsync(request.Email) is not null)
throw new ConflictException($"Email '{request.Email}' đã tồn tại.");
var user = new User
{
UserName = request.Email,
Email = request.Email,
FullName = request.FullName,
EmailConfirmed = true,
IsActive = true,
CreatedAt = dateTime.UtcNow,
};
var result = await userManager.CreateAsync(user, request.Password);
if (!result.Succeeded)
throw new ValidationException(result.Errors.Select(e => new FluentValidation.Results.ValidationFailure("Password", e.Description)));
// Assign roles
foreach (var roleName in request.Roles.Distinct())
{
if (await roleManager.RoleExistsAsync(roleName))
await userManager.AddToRoleAsync(user, roleName);
}
return user.Id;
}
}
// ========== UPDATE ==========
public record UpdateUserCommand(Guid Id, string FullName, bool IsActive) : IRequest;
public class UpdateUserCommandValidator : AbstractValidator<UpdateUserCommand>
{
public UpdateUserCommandValidator()
{
RuleFor(x => x.Id).NotEmpty();
RuleFor(x => x.FullName).NotEmpty().MaximumLength(200);
}
}
public class UpdateUserCommandHandler(UserManager<User> userManager, ICurrentUser currentUser)
: IRequestHandler<UpdateUserCommand>
{
public async Task Handle(UpdateUserCommand request, CancellationToken ct)
{
var user = await userManager.FindByIdAsync(request.Id.ToString())
?? throw new NotFoundException("User", request.Id);
// Self-disable protection: admin không thể tự deactivate
if (!request.IsActive && user.Id == currentUser.UserId)
throw new ForbiddenException("Không thể tự vô hiệu hóa tài khoản của mình.");
user.FullName = request.FullName;
user.IsActive = request.IsActive;
await userManager.UpdateAsync(user);
}
}
// ========== ASSIGN ROLES (replace full set) ==========
public record AssignRolesCommand(Guid Id, List<string> Roles) : IRequest;
public class AssignRolesCommandValidator : AbstractValidator<AssignRolesCommand>
{
public AssignRolesCommandValidator()
{
RuleFor(x => x.Id).NotEmpty();
RuleFor(x => x.Roles).NotNull();
}
}
public class AssignRolesCommandHandler(
UserManager<User> userManager,
RoleManager<Role> roleManager,
ICurrentUser currentUser) : IRequestHandler<AssignRolesCommand>
{
public async Task Handle(AssignRolesCommand request, CancellationToken ct)
{
var user = await userManager.FindByIdAsync(request.Id.ToString())
?? throw new NotFoundException("User", request.Id);
var current = await userManager.GetRolesAsync(user);
var target = request.Roles.Distinct().ToList();
// Self-demote protection: admin không thể tự gỡ role Admin khỏi mình
if (user.Id == currentUser.UserId
&& current.Contains(AppRoles.Admin)
&& !target.Contains(AppRoles.Admin))
{
throw new ForbiddenException("Không thể tự gỡ role Admin khỏi mình.");
}
var toRemove = current.Except(target).ToList();
var toAdd = target.Except(current).ToList();
if (toRemove.Count > 0) await userManager.RemoveFromRolesAsync(user, toRemove);
foreach (var roleName in toAdd)
{
if (await roleManager.RoleExistsAsync(roleName))
await userManager.AddToRoleAsync(user, roleName);
}
}
}
// ========== RESET PASSWORD (admin) ==========
public record ResetPasswordCommand(Guid Id, string NewPassword) : IRequest;
public class ResetPasswordCommandValidator : AbstractValidator<ResetPasswordCommand>
{
public ResetPasswordCommandValidator()
{
RuleFor(x => x.Id).NotEmpty();
RuleFor(x => x.NewPassword).NotEmpty().MinimumLength(8);
}
}
public class ResetPasswordCommandHandler(UserManager<User> userManager)
: IRequestHandler<ResetPasswordCommand>
{
public async Task Handle(ResetPasswordCommand request, CancellationToken ct)
{
var user = await userManager.FindByIdAsync(request.Id.ToString())
?? throw new NotFoundException("User", request.Id);
// Admin flow: remove + set password (không cần token)
await userManager.RemovePasswordAsync(user);
var result = await userManager.AddPasswordAsync(user, request.NewPassword);
if (!result.Succeeded)
throw new ValidationException(result.Errors.Select(e => new FluentValidation.Results.ValidationFailure("NewPassword", e.Description)));
// Invalidate refresh token → force re-login
user.RefreshToken = null;
user.RefreshTokenExpiresAt = null;
await userManager.UpdateAsync(user);
// Unlock nếu đang lock
await userManager.ResetAccessFailedCountAsync(user);
await userManager.SetLockoutEndDateAsync(user, null);
}
}
// ========== UNLOCK ==========
public record UnlockUserCommand(Guid Id) : IRequest;
public class UnlockUserCommandHandler(UserManager<User> userManager) : IRequestHandler<UnlockUserCommand>
{
public async Task Handle(UnlockUserCommand request, CancellationToken ct)
{
var user = await userManager.FindByIdAsync(request.Id.ToString())
?? throw new NotFoundException("User", request.Id);
await userManager.SetLockoutEndDateAsync(user, null);
await userManager.ResetAccessFailedCountAsync(user);
}
}