[CLAUDE] Phase1: foundation - BE Clean Arch + Identity + JWT + 2 FE React + login E2E
Backend (.NET 10): - Domain: BaseEntity/AuditableEntity, ContractType/Phase/ApprovalDecision enums, User/Role (Identity<Guid>), AppRoles (12 const) - Application: IApplicationDbContext/ICurrentUser/IDateTime/IJwtTokenService, custom exceptions, ValidationBehavior (MediatR pipeline), Auth CQRS (Login/Refresh/Me), DependencyInjection - Infrastructure: ApplicationDbContext (IdentityDbContext), AuditingInterceptor (auto audit + soft delete), DbInitializer (seed 12 role + admin), DesignTimeDbContextFactory, JwtTokenService, DateTimeService, DI - Api: CurrentUserService, GlobalExceptionMiddleware (ProblemDetails), AuthController, Program.cs rewrite (Serilog + JWT + CORS + Swagger), appsettings + launchSettings (port 5443) - Migration Init applied to SolutionErp_Dev LocalDB Frontend (React 19 + Vite 8 + Tailwind 4): - fe-admin (:8082 blue) + fe-user (:8080 emerald) - shared structure, khac menu + brand color - Tailwind 4 via @tailwindcss/vite plugin, theme brand colors - AuthContext (localStorage token), ProtectedRoute, Layout (sidebar + header) - UI kit: Button/Input/Label (CVA + Tailwind) - LoginPage voi toast error, DashboardPage/InboxPage placeholder - Axios interceptor: auto Bearer + 401 redirect - TanStack Query client, React Router 7, Sonner toast Package downgrades (do .NET 10 / TS 6 compat): - MediatR 14 -> 12.4.1 (v14 breaking changes) - Swashbuckle 10 -> 6.9.0 (v10 khong tuong thich OpenApi 2) - Removed Microsoft.AspNetCore.OpenApi (conflict voi Swashbuckle) E2E verified: POST /api/auth/login qua Vite proxy ca 2 FE -> JWT + user info Credentials seed: admin@solutionerp.local / Admin@123456 Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
40
src/Backend/SolutionErp.Api/Controllers/AuthController.cs
Normal file
40
src/Backend/SolutionErp.Api/Controllers/AuthController.cs
Normal file
@ -0,0 +1,40 @@
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using SolutionErp.Application.Auth.Commands.Login;
|
||||
using SolutionErp.Application.Auth.Commands.Refresh;
|
||||
using SolutionErp.Application.Auth.Dtos;
|
||||
using SolutionErp.Application.Auth.Queries.Me;
|
||||
|
||||
namespace SolutionErp.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/auth")]
|
||||
public class AuthController : ControllerBase
|
||||
{
|
||||
private readonly IMediator _mediator;
|
||||
|
||||
public AuthController(IMediator mediator) => _mediator = mediator;
|
||||
|
||||
[HttpPost("login")]
|
||||
[AllowAnonymous]
|
||||
public async Task<ActionResult<AuthResponseDto>> Login([FromBody] LoginCommand command, CancellationToken ct)
|
||||
=> Ok(await _mediator.Send(command, ct));
|
||||
|
||||
[HttpPost("refresh")]
|
||||
[AllowAnonymous]
|
||||
public async Task<ActionResult<AuthResponseDto>> Refresh([FromBody] RefreshTokenCommand command, CancellationToken ct)
|
||||
=> Ok(await _mediator.Send(command, ct));
|
||||
|
||||
[HttpGet("me")]
|
||||
[Authorize]
|
||||
public async Task<ActionResult<UserInfoDto>> Me(CancellationToken ct)
|
||||
=> Ok(await _mediator.Send(new GetMeQuery(), ct));
|
||||
|
||||
[HttpPost("logout")]
|
||||
[Authorize]
|
||||
public IActionResult Logout()
|
||||
{
|
||||
return NoContent();
|
||||
}
|
||||
}
|
||||
@ -1,25 +0,0 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace SolutionErp.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("[controller]")]
|
||||
public class WeatherForecastController : ControllerBase
|
||||
{
|
||||
private static readonly string[] Summaries =
|
||||
[
|
||||
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
|
||||
];
|
||||
|
||||
[HttpGet(Name = "GetWeatherForecast")]
|
||||
public IEnumerable<WeatherForecast> Get()
|
||||
{
|
||||
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
|
||||
{
|
||||
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
|
||||
TemperatureC = Random.Shared.Next(-20, 55),
|
||||
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
|
||||
})
|
||||
.ToArray();
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,64 @@
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using SolutionErp.Application.Common.Exceptions;
|
||||
|
||||
namespace SolutionErp.Api.Middleware;
|
||||
|
||||
public class GlobalExceptionMiddleware
|
||||
{
|
||||
private readonly RequestDelegate _next;
|
||||
private readonly ILogger<GlobalExceptionMiddleware> _logger;
|
||||
|
||||
public GlobalExceptionMiddleware(RequestDelegate next, ILogger<GlobalExceptionMiddleware> logger)
|
||||
{
|
||||
_next = next;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _next(context);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await HandleAsync(context, ex);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task HandleAsync(HttpContext context, Exception ex)
|
||||
{
|
||||
var (status, type, title) = ex switch
|
||||
{
|
||||
ValidationException => ((int)HttpStatusCode.BadRequest, "https://tools.ietf.org/html/rfc9110#section-15.5.1", "Dữ liệu không hợp lệ"),
|
||||
NotFoundException => ((int)HttpStatusCode.NotFound, "https://tools.ietf.org/html/rfc9110#section-15.5.5", "Không tìm thấy"),
|
||||
UnauthorizedException => ((int)HttpStatusCode.Unauthorized, "https://tools.ietf.org/html/rfc9110#section-15.5.2", "Chưa xác thực"),
|
||||
ForbiddenException => ((int)HttpStatusCode.Forbidden, "https://tools.ietf.org/html/rfc9110#section-15.5.4", "Bị từ chối"),
|
||||
ConflictException => ((int)HttpStatusCode.Conflict, "https://tools.ietf.org/html/rfc9110#section-15.5.10", "Xung đột dữ liệu"),
|
||||
_ => ((int)HttpStatusCode.InternalServerError, "https://tools.ietf.org/html/rfc9110#section-15.6.1", "Lỗi hệ thống"),
|
||||
};
|
||||
|
||||
if (status >= 500)
|
||||
_logger.LogError(ex, "Unhandled exception: {Message}", ex.Message);
|
||||
else
|
||||
_logger.LogWarning(ex, "Handled exception: {Message}", ex.Message);
|
||||
|
||||
var problem = new
|
||||
{
|
||||
type,
|
||||
title,
|
||||
status,
|
||||
detail = ex.Message,
|
||||
errors = (ex as ValidationException)?.Errors,
|
||||
traceId = context.TraceIdentifier,
|
||||
};
|
||||
|
||||
context.Response.ContentType = "application/problem+json";
|
||||
context.Response.StatusCode = status;
|
||||
await context.Response.WriteAsync(JsonSerializer.Serialize(problem, new JsonSerializerOptions
|
||||
{
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||
}));
|
||||
}
|
||||
}
|
||||
@ -1,23 +1,120 @@
|
||||
using System.Text;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Microsoft.OpenApi.Models;
|
||||
using Serilog;
|
||||
using SolutionErp.Api.Middleware;
|
||||
using SolutionErp.Api.Services;
|
||||
using SolutionErp.Application;
|
||||
using SolutionErp.Application.Common.Interfaces;
|
||||
using SolutionErp.Infrastructure;
|
||||
using SolutionErp.Infrastructure.Identity;
|
||||
using SolutionErp.Infrastructure.Persistence;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// Add services to the container.
|
||||
// ---------- Logging (Serilog) ----------
|
||||
builder.Host.UseSerilog((ctx, cfg) => cfg
|
||||
.ReadFrom.Configuration(ctx.Configuration)
|
||||
.Enrich.FromLogContext()
|
||||
.WriteTo.Console());
|
||||
|
||||
// ---------- Core services ----------
|
||||
builder.Services.AddControllers();
|
||||
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
|
||||
builder.Services.AddOpenApi();
|
||||
builder.Services.AddHttpContextAccessor();
|
||||
builder.Services.AddScoped<ICurrentUser, CurrentUserService>();
|
||||
|
||||
builder.Services.AddApplication();
|
||||
builder.Services.AddInfrastructure(builder.Configuration);
|
||||
|
||||
// ---------- JWT auth ----------
|
||||
var jwt = builder.Configuration.GetSection(JwtSettings.SectionName).Get<JwtSettings>()
|
||||
?? throw new InvalidOperationException("Missing Jwt settings");
|
||||
|
||||
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
.AddJwtBearer(options =>
|
||||
{
|
||||
options.RequireHttpsMetadata = !builder.Environment.IsDevelopment();
|
||||
options.SaveToken = true;
|
||||
options.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuer = true,
|
||||
ValidateAudience = true,
|
||||
ValidateLifetime = true,
|
||||
ValidateIssuerSigningKey = true,
|
||||
ValidIssuer = jwt.Issuer,
|
||||
ValidAudience = jwt.Audience,
|
||||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwt.Secret)),
|
||||
ClockSkew = TimeSpan.FromMinutes(1),
|
||||
};
|
||||
});
|
||||
builder.Services.AddAuthorization();
|
||||
|
||||
// ---------- CORS (2 FE dev origins) ----------
|
||||
builder.Services.AddCors(opts =>
|
||||
{
|
||||
opts.AddDefaultPolicy(p => p
|
||||
.WithOrigins("http://localhost:8080", "http://localhost:8082")
|
||||
.AllowAnyHeader()
|
||||
.AllowAnyMethod()
|
||||
.AllowCredentials());
|
||||
});
|
||||
|
||||
// ---------- Swagger ----------
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddSwaggerGen(c =>
|
||||
{
|
||||
c.SwaggerDoc("v1", new OpenApiInfo { Title = "SolutionErp API", Version = "v1" });
|
||||
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
|
||||
{
|
||||
Name = "Authorization",
|
||||
Type = SecuritySchemeType.Http,
|
||||
Scheme = "bearer",
|
||||
BearerFormat = "JWT",
|
||||
In = ParameterLocation.Header,
|
||||
Description = "JWT Bearer token — nhập chỉ token, Swagger tự thêm 'Bearer '.",
|
||||
});
|
||||
c.AddSecurityRequirement(new OpenApiSecurityRequirement
|
||||
{
|
||||
{
|
||||
new OpenApiSecurityScheme
|
||||
{
|
||||
Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" },
|
||||
},
|
||||
Array.Empty<string>()
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
// ---------- Pipeline ----------
|
||||
app.UseMiddleware<GlobalExceptionMiddleware>();
|
||||
app.UseSerilogRequestLogging();
|
||||
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.MapOpenApi();
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "SolutionErp API v1"));
|
||||
}
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
|
||||
app.UseCors();
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
|
||||
app.MapControllers();
|
||||
|
||||
// ---------- DB init + seed ----------
|
||||
if (!args.Contains("--no-db-init"))
|
||||
{
|
||||
try
|
||||
{
|
||||
await DbInitializer.InitializeAsync(app.Services);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
app.Logger.LogError(ex, "DB initialization failed — app vẫn chạy, check connection string.");
|
||||
}
|
||||
}
|
||||
|
||||
app.Run();
|
||||
|
||||
@ -1,20 +1,21 @@
|
||||
{
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/launchsettings.json",
|
||||
"profiles": {
|
||||
"http": {
|
||||
"https": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": false,
|
||||
"applicationUrl": "http://localhost:5235",
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"applicationUrl": "https://localhost:5443;http://localhost:5444",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"https": {
|
||||
"http": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": false,
|
||||
"applicationUrl": "https://localhost:7241;http://localhost:5235",
|
||||
"applicationUrl": "http://localhost:5444",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
|
||||
34
src/Backend/SolutionErp.Api/Services/CurrentUserService.cs
Normal file
34
src/Backend/SolutionErp.Api/Services/CurrentUserService.cs
Normal file
@ -0,0 +1,34 @@
|
||||
using System.Security.Claims;
|
||||
using SolutionErp.Application.Common.Interfaces;
|
||||
|
||||
namespace SolutionErp.Api.Services;
|
||||
|
||||
public class CurrentUserService : ICurrentUser
|
||||
{
|
||||
private readonly IHttpContextAccessor _accessor;
|
||||
|
||||
public CurrentUserService(IHttpContextAccessor accessor)
|
||||
{
|
||||
_accessor = accessor;
|
||||
}
|
||||
|
||||
private ClaimsPrincipal? User => _accessor.HttpContext?.User;
|
||||
|
||||
public Guid? UserId
|
||||
{
|
||||
get
|
||||
{
|
||||
var sub = User?.FindFirstValue(ClaimTypes.NameIdentifier)
|
||||
?? User?.FindFirstValue("sub");
|
||||
return Guid.TryParse(sub, out var id) ? id : null;
|
||||
}
|
||||
}
|
||||
|
||||
public string? Email => User?.FindFirstValue(ClaimTypes.Email);
|
||||
public string? FullName => User?.FindFirstValue("fullName");
|
||||
|
||||
public IReadOnlyList<string> Roles =>
|
||||
User?.FindAll(ClaimTypes.Role).Select(c => c.Value).ToList() ?? new List<string>();
|
||||
|
||||
public bool IsAuthenticated => User?.Identity?.IsAuthenticated ?? false;
|
||||
}
|
||||
@ -8,9 +8,12 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.6" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.4" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.6">
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Serilog.AspNetCore" Version="10.0.0" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="10.1.7" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.9.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@ -1,12 +0,0 @@
|
||||
namespace SolutionErp.Api;
|
||||
|
||||
public class WeatherForecast
|
||||
{
|
||||
public DateOnly Date { get; set; }
|
||||
|
||||
public int TemperatureC { get; set; }
|
||||
|
||||
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
|
||||
|
||||
public string? Summary { get; set; }
|
||||
}
|
||||
@ -1,8 +1,18 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
"ConnectionStrings": {
|
||||
"Default": "Server=(localdb)\\MSSQLLocalDB;Database=SolutionErp_Dev;Trusted_Connection=True;MultipleActiveResultSets=true;TrustServerCertificate=true"
|
||||
},
|
||||
"Jwt": {
|
||||
"Secret": "dev_only_secret_min_32_chars_NOT_for_production_please_change"
|
||||
},
|
||||
"Serilog": {
|
||||
"MinimumLevel": {
|
||||
"Default": "Debug",
|
||||
"Override": {
|
||||
"Microsoft": "Information",
|
||||
"Microsoft.EntityFrameworkCore": "Information",
|
||||
"System": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,8 +1,22 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"ConnectionStrings": {
|
||||
"Default": "Server=(localdb)\\MSSQLLocalDB;Database=SolutionErp;Trusted_Connection=True;MultipleActiveResultSets=true;TrustServerCertificate=true"
|
||||
},
|
||||
"Jwt": {
|
||||
"Issuer": "SolutionErp.Api",
|
||||
"Audience": "SolutionErp.Client",
|
||||
"Secret": "CHANGE_ME_minimum_32_chars_production_secret_here_please",
|
||||
"AccessTokenExpiryMinutes": 60,
|
||||
"RefreshTokenExpiryDays": 7
|
||||
},
|
||||
"Serilog": {
|
||||
"MinimumLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
"Override": {
|
||||
"Microsoft": "Warning",
|
||||
"Microsoft.EntityFrameworkCore": "Warning",
|
||||
"System": "Warning"
|
||||
}
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
|
||||
Reference in New Issue
Block a user