Complete MVP implementation (Étape 1) covering: - Domain: primitives (Entity<TId>, ValueObject), 10 entities, 6 enums - EF Core: AppDbContext + Identity, 8 EntityTypeConfigurations, audit/soft-delete interceptors, initial migration - Application: service interfaces, DTOs, FluentValidation, ServiceResult pattern - Security: Identity + JWT + API Key multi-auth, role-based permissions, constant-time key validation - API: Auth/Sites/Agents controllers with explicit auth scheme policies - Workers: Hangfire PostgreSQL setup with schema isolation, HeartbeatMonitorJob - Agent: registration service + 30s heartbeat loop - Docker: multi-stage Dockerfiles for central + agent, docker-compose.yml - CI/CD: GitHub Actions pipeline with build+test and Docker build - Tests: 13 domain tests (Site, Agent, Camera entities) Architecture decisions per deliberation council: - API Key via AuthenticationHandler<T> (not middleware) - Explicit [Authorize(AuthenticationSchemes)] on all endpoints - Event/Recording/Person/Vehicle deferred from initial migration - Hangfire compatible with .NET 10 (v1.8.17)
110 lines
3.6 KiB
C#
110 lines
3.6 KiB
C#
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Security.Claims;
|
|
using System.Security.Cryptography;
|
|
using System.Text;
|
|
using Heimdall.Domain.Entities;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
|
|
namespace Heimdall.Infrastructure.Security;
|
|
|
|
public interface IJwtService
|
|
{
|
|
(string token, DateTime expiresAt) GenerateAccessToken(AppUser user, IList<string> roles, IList<string> permissions);
|
|
string GenerateRefreshToken();
|
|
ClaimsPrincipal? ValidateRefreshToken(string refreshToken);
|
|
string? GetUserIdFromExpiredToken(string token);
|
|
}
|
|
|
|
public class JwtService : IJwtService
|
|
{
|
|
private readonly IConfiguration _configuration;
|
|
|
|
public JwtService(IConfiguration configuration)
|
|
{
|
|
_configuration = configuration;
|
|
}
|
|
|
|
public (string token, DateTime expiresAt) GenerateAccessToken(AppUser user, IList<string> roles, IList<string> permissions)
|
|
{
|
|
var key = new SymmetricSecurityKey(
|
|
Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]
|
|
?? throw new InvalidOperationException("JWT key is not configured")));
|
|
|
|
var expiresAt = DateTime.UtcNow.AddMinutes(
|
|
double.TryParse(_configuration["Jwt:AccessTokenExpiryMinutes"], out var minutes) ? minutes : 15);
|
|
|
|
var claims = new List<Claim>
|
|
{
|
|
new(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
|
|
new(JwtRegisteredClaimNames.Email, user.Email ?? ""),
|
|
new(JwtRegisteredClaimNames.Name, user.DisplayName),
|
|
new("role", string.Join(",", roles)),
|
|
};
|
|
|
|
foreach (var permission in permissions)
|
|
{
|
|
claims.Add(new Claim("permission", permission));
|
|
}
|
|
|
|
var token = new JwtSecurityToken(
|
|
issuer: _configuration["Jwt:Issuer"] ?? "heimdall",
|
|
audience: _configuration["Jwt:Audience"] ?? "heimdall-api",
|
|
claims: claims,
|
|
expires: expiresAt,
|
|
signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256));
|
|
|
|
return (new JwtSecurityTokenHandler().WriteToken(token), expiresAt);
|
|
}
|
|
|
|
public string GenerateRefreshToken()
|
|
{
|
|
var randomBytes = new byte[64];
|
|
using var rng = RandomNumberGenerator.Create();
|
|
rng.GetBytes(randomBytes);
|
|
return Convert.ToBase64String(randomBytes);
|
|
}
|
|
|
|
public ClaimsPrincipal? ValidateRefreshToken(string refreshToken)
|
|
{
|
|
var key = new SymmetricSecurityKey(
|
|
Encoding.UTF8.GetBytes(_configuration["Jwt:RefreshKey"]
|
|
?? _configuration["Jwt:Key"]
|
|
?? throw new InvalidOperationException("JWT key is not configured")));
|
|
|
|
try
|
|
{
|
|
var handler = new JwtSecurityTokenHandler();
|
|
return handler.ValidateToken(refreshToken, new TokenValidationParameters
|
|
{
|
|
ValidateIssuerSigningKey = true,
|
|
IssuerSigningKey = key,
|
|
ValidateIssuer = true,
|
|
ValidIssuer = _configuration["Jwt:Issuer"] ?? "heimdall",
|
|
ValidateAudience = true,
|
|
ValidAudience = _configuration["Jwt:Audience"] ?? "heimdall-api",
|
|
ValidateLifetime = true,
|
|
ClockSkew = TimeSpan.Zero
|
|
}, out _);
|
|
}
|
|
catch
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
|
|
public string? GetUserIdFromExpiredToken(string token)
|
|
{
|
|
try
|
|
{
|
|
var handler = new JwtSecurityTokenHandler();
|
|
var jwtToken = handler.ReadJwtToken(token);
|
|
return jwtToken.Subject;
|
|
}
|
|
catch
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
}
|