[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:
68
src/Backend/SolutionErp.Api/Controllers/UsersController.cs
Normal file
68
src/Backend/SolutionErp.Api/Controllers/UsersController.cs
Normal file
@ -0,0 +1,68 @@
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using SolutionErp.Application.Common.Models;
|
||||
using SolutionErp.Application.Users;
|
||||
|
||||
namespace SolutionErp.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/users")]
|
||||
[Authorize(Policy = "Users.Read")]
|
||||
public class UsersController(IMediator mediator) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
public async Task<ActionResult<PagedResult<UserDto>>> List(
|
||||
[FromQuery] int page = 1, [FromQuery] int pageSize = 20,
|
||||
[FromQuery] string? search = null, [FromQuery] bool sortDesc = true,
|
||||
CancellationToken ct = default)
|
||||
=> Ok(await mediator.Send(new ListUsersQuery { Page = page, PageSize = pageSize, Search = search, SortDesc = sortDesc }, ct));
|
||||
|
||||
[HttpGet("{id:guid}")]
|
||||
public async Task<ActionResult<UserDto>> Get(Guid id, CancellationToken ct)
|
||||
=> Ok(await mediator.Send(new GetUserQuery(id), ct));
|
||||
|
||||
[HttpPost]
|
||||
[Authorize(Policy = "Users.Create")]
|
||||
public async Task<ActionResult<object>> Create([FromBody] CreateUserCommand cmd, CancellationToken ct)
|
||||
{
|
||||
var id = await mediator.Send(cmd, ct);
|
||||
return CreatedAtAction(nameof(Get), new { id }, new { id });
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}")]
|
||||
[Authorize(Policy = "Users.Update")]
|
||||
public async Task<IActionResult> Update(Guid id, [FromBody] UpdateUserCommand cmd, CancellationToken ct)
|
||||
{
|
||||
if (id != cmd.Id) return BadRequest(new { detail = "ID không khớp" });
|
||||
await mediator.Send(cmd, ct);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}/roles")]
|
||||
[Authorize(Policy = "Users.Update")]
|
||||
public async Task<IActionResult> AssignRoles(Guid id, [FromBody] AssignRolesBody body, CancellationToken ct)
|
||||
{
|
||||
await mediator.Send(new AssignRolesCommand(id, body.Roles), ct);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
[HttpPost("{id:guid}/reset-password")]
|
||||
[Authorize(Policy = "Users.Update")]
|
||||
public async Task<IActionResult> ResetPassword(Guid id, [FromBody] ResetPasswordBody body, CancellationToken ct)
|
||||
{
|
||||
await mediator.Send(new ResetPasswordCommand(id, body.NewPassword), ct);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
[HttpPost("{id:guid}/unlock")]
|
||||
[Authorize(Policy = "Users.Update")]
|
||||
public async Task<IActionResult> Unlock(Guid id, CancellationToken ct)
|
||||
{
|
||||
await mediator.Send(new UnlockUserCommand(id), ct);
|
||||
return NoContent();
|
||||
}
|
||||
}
|
||||
|
||||
public record AssignRolesBody(List<string> Roles);
|
||||
public record ResetPasswordBody(string NewPassword);
|
||||
@ -0,0 +1,42 @@
|
||||
namespace SolutionErp.Api.Middleware;
|
||||
|
||||
// Thêm security headers theo OWASP + Mozilla Observatory best practices.
|
||||
// Xem docs/guides/security-checklist.md §A05.
|
||||
public class SecurityHeadersMiddleware(RequestDelegate next)
|
||||
{
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
var headers = context.Response.Headers;
|
||||
|
||||
// Ẩn server fingerprint
|
||||
headers.Remove("Server");
|
||||
headers.Remove("X-Powered-By");
|
||||
headers.Remove("X-AspNet-Version");
|
||||
headers.Remove("X-AspNetMvc-Version");
|
||||
|
||||
// Security headers
|
||||
headers["X-Content-Type-Options"] = "nosniff";
|
||||
headers["X-Frame-Options"] = "DENY";
|
||||
headers["Referrer-Policy"] = "strict-origin-when-cross-origin";
|
||||
headers["X-Permitted-Cross-Domain-Policies"] = "none";
|
||||
headers["Permissions-Policy"] = "geolocation=(), microphone=(), camera=(), payment=()";
|
||||
|
||||
// CSP chỉ áp dụng ở non-Swagger (Swagger dùng inline script/style)
|
||||
var isSwagger = context.Request.Path.StartsWithSegments("/swagger");
|
||||
if (!isSwagger)
|
||||
{
|
||||
headers["Content-Security-Policy"] =
|
||||
"default-src 'self'; " +
|
||||
"img-src 'self' data:; " +
|
||||
"style-src 'self' 'unsafe-inline'; " + // Tailwind cần inline styles ở runtime
|
||||
"script-src 'self'; " +
|
||||
"font-src 'self' data:; " +
|
||||
"connect-src 'self'; " +
|
||||
"frame-ancestors 'none'; " +
|
||||
"base-uri 'self'; " +
|
||||
"form-action 'self'";
|
||||
}
|
||||
|
||||
await next(context);
|
||||
}
|
||||
}
|
||||
@ -146,6 +146,7 @@ builder.Services.AddSwaggerGen(c =>
|
||||
var app = builder.Build();
|
||||
|
||||
// ---------- Pipeline ----------
|
||||
app.UseMiddleware<SecurityHeadersMiddleware>();
|
||||
app.UseMiddleware<GlobalExceptionMiddleware>();
|
||||
app.UseSerilogRequestLogging();
|
||||
|
||||
|
||||
Reference in New Issue
Block a user