Základní backend: migrace, autentizace JWT, role, Swagger
- Helpdesk.Migrator (DbUp) aplikuje db/migrations, evidence v schema_version - Domain/Application/Infrastructure/Api podle Clean Architecture - registrace, ověření e-mailu, login, refresh s rotací, logout, reset hesla - JWT podle RFC 7519 evidované jen podle jti v auth_token - správa uživatelů a rolí, číselníky, ProblemDetails, Swagger UI - Docker Compose (db, migrator, api), oddělené DB účty - notifikace mají cizí klíče na issue a proposal - unit testy domény a zabezpečení Closes #1, closes #2, closes #3, closes #4, closes #5, closes #9
This commit is contained in:
1 parent
fc76be7d69
commit
a51d386278
64 files changed
+4394
-1
No files matched your search
@@ -0,0 +1,45 @@
|
||||
using Helpdesk.Infrastructure.Persistence;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Helpdesk.Infrastructure.Background;
|
||||
|
||||
/// <summary>Jednou denně smaže záznamy <c>auth_token</c> 30 dní po vypršení; do té doby slouží jako audit (kap. 10.1).</summary>
|
||||
internal sealed partial class AuthTokenCleanupService(
|
||||
IServiceScopeFactory scopes,
|
||||
TimeProvider clock,
|
||||
ILogger<AuthTokenCleanupService> logger) : BackgroundService
|
||||
{
|
||||
private static readonly TimeSpan RetentionAfterExpiry = TimeSpan.FromDays(30);
|
||||
private static readonly TimeSpan Interval = TimeSpan.FromDays(1);
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
using var timer = new PeriodicTimer(Interval, clock);
|
||||
do
|
||||
{
|
||||
try
|
||||
{
|
||||
using var scope = scopes.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||
var threshold = clock.GetUtcNow().UtcDateTime - RetentionAfterExpiry;
|
||||
|
||||
var deleted = await db.AuthTokens.Where(t => t.ExpiresAt < threshold).ExecuteDeleteAsync(stoppingToken);
|
||||
LogDeleted(deleted);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
LogFailed(ex);
|
||||
}
|
||||
}
|
||||
while (await timer.WaitForNextTickAsync(stoppingToken));
|
||||
}
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Information, Message = "Úklid auth_token: smazáno {Count} prošlých záznamů.")]
|
||||
private partial void LogDeleted(int count);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Error, Message = "Úklid auth_token selhal.")]
|
||||
private partial void LogFailed(Exception ex);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
using Helpdesk.Application.Abstractions;
|
||||
using Helpdesk.Infrastructure.Background;
|
||||
using Helpdesk.Infrastructure.Email;
|
||||
using Helpdesk.Infrastructure.Persistence;
|
||||
using Helpdesk.Infrastructure.Security;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Helpdesk.Infrastructure;
|
||||
|
||||
public static class DependencyInjection
|
||||
{
|
||||
public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
var connectionString = configuration.GetConnectionString("Helpdesk")
|
||||
?? throw new InvalidOperationException("Chybí připojovací řetězec ConnectionStrings:Helpdesk.");
|
||||
|
||||
services.AddSingleton(TimeProvider.System);
|
||||
services.Configure<JwtOptions>(configuration.GetSection(JwtOptions.Section));
|
||||
services.Configure<EncryptionOptions>(configuration.GetSection(EncryptionOptions.Section));
|
||||
|
||||
services.AddSingleton<FieldEncryptor>();
|
||||
services.AddSingleton<CreatedAtInterceptor>();
|
||||
services.AddDbContext<HelpdeskDbContext>((sp, options) => options
|
||||
.UseMySql(connectionString, new MariaDbServerVersion(new Version(11, 4)))
|
||||
.UseSnakeCaseNamingConvention()
|
||||
.AddInterceptors(sp.GetRequiredService<CreatedAtInterceptor>()));
|
||||
services.AddScoped<IAppDbContext>(sp => sp.GetRequiredService<HelpdeskDbContext>());
|
||||
|
||||
services.AddSingleton<IPasswordHasher, BCryptPasswordHasher>();
|
||||
services.AddSingleton<ITokenService, JwtTokenService>();
|
||||
services.AddSingleton<IRevokedTokenStore, RevokedTokenStore>();
|
||||
services.AddSingleton<IEmailSender, LoggingEmailSender>();
|
||||
|
||||
services.AddHostedService<RevokedTokenStoreLoader>();
|
||||
services.AddHostedService<AdminSeeder>();
|
||||
services.AddHostedService<AuthTokenCleanupService>();
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using Helpdesk.Application.Abstractions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Helpdesk.Infrastructure.Email;
|
||||
|
||||
/// <summary>
|
||||
/// Vývojová náhrada odesílání e-mailů – obsah zapíše do logu (odkaz pro ověření e-mailu je tak vidět
|
||||
/// v <c>docker compose logs api</c>). Odesílání přes SMTP (MailKit + Mailpit) přijde s notifikacemi.
|
||||
/// </summary>
|
||||
internal sealed partial class LoggingEmailSender(ILogger<LoggingEmailSender> logger) : IEmailSender
|
||||
{
|
||||
public Task SendAsync(string to, string subject, string body, CancellationToken cancellationToken = default)
|
||||
{
|
||||
LogEmail(to, subject, body);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Information, Message = "E-mail pro {To} – {Subject}:\n{Body}")]
|
||||
private partial void LogEmail(string to, string subject, string body);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Helpdesk.Application\Helpdesk.Application.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" />
|
||||
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" />
|
||||
<PackageReference Include="MySqlConnector" />
|
||||
<PackageReference Include="EFCore.NamingConventions" />
|
||||
<PackageReference Include="BCrypt.Net-Next" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" />
|
||||
<PackageReference Include="Microsoft.Extensions.Caching.Memory" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="Helpdesk.UnitTests" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,46 @@
|
||||
using Helpdesk.Application.Abstractions;
|
||||
using Helpdesk.Domain.Users;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Helpdesk.Infrastructure.Persistence;
|
||||
|
||||
/// <summary>
|
||||
/// Při startu vytvoří účet administrátora z <c>ADMIN_EMAIL</c> a <c>ADMIN_PASSWORD</c>, pokud ještě neexistuje.
|
||||
/// Admin není v migracích, aby hash hesla vznikl stejným algoritmem jako u ostatních uživatelů.
|
||||
/// </summary>
|
||||
internal sealed partial class AdminSeeder(
|
||||
IServiceScopeFactory scopes,
|
||||
IConfiguration configuration,
|
||||
ILogger<AdminSeeder> logger) : IHostedService
|
||||
{
|
||||
public async Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var email = configuration["ADMIN_EMAIL"];
|
||||
var password = configuration["ADMIN_PASSWORD"];
|
||||
if (string.IsNullOrWhiteSpace(email) || string.IsNullOrWhiteSpace(password))
|
||||
return;
|
||||
|
||||
using var scope = scopes.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||
var hasher = scope.ServiceProvider.GetRequiredService<IPasswordHasher>();
|
||||
|
||||
var normalized = User.NormalizeEmail(email);
|
||||
if (await db.Users.AnyAsync(u => u.EmailNormalized == normalized, cancellationToken))
|
||||
return;
|
||||
|
||||
var admin = User.Create(email, hasher.Hash(password), "Administrátor", "Systému", UserRole.Admin);
|
||||
admin.ConfirmEmail();
|
||||
db.Users.Add(admin);
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
LogCreated(email);
|
||||
}
|
||||
|
||||
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Information, Message = "Vytvořen účet administrátora {Email}.")]
|
||||
private partial void LogCreated(string email);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using Helpdesk.Domain.Auth;
|
||||
using Helpdesk.Domain.Catalogs;
|
||||
using Helpdesk.Domain.Users;
|
||||
using Helpdesk.Infrastructure.Security;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
|
||||
namespace Helpdesk.Infrastructure.Persistence;
|
||||
|
||||
internal sealed class UserConfiguration(FieldEncryptor encryptor) : IEntityTypeConfiguration<User>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<User> b)
|
||||
{
|
||||
b.ToTable("app_user");
|
||||
b.HasKey(u => u.Id);
|
||||
b.Property(u => u.Email).HasMaxLength(254);
|
||||
b.Property(u => u.EmailNormalized).HasMaxLength(254);
|
||||
b.HasIndex(u => u.EmailNormalized).IsUnique();
|
||||
b.Property(u => u.Role).HasConversion<EnumCodeConverter<UserRole>>().HasMaxLength(30);
|
||||
b.Property(u => u.Phone)
|
||||
.HasColumnName("phone_encrypted")
|
||||
.HasConversion(encryptor.StringToCipherConverter)
|
||||
.HasMaxLength(512);
|
||||
b.Ignore(u => u.FullName);
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class AuthTokenConfiguration : IEntityTypeConfiguration<AuthToken>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<AuthToken> b)
|
||||
{
|
||||
b.ToTable("auth_token");
|
||||
b.HasKey(t => t.Jti);
|
||||
b.Property(t => t.Jti).HasMaxLength(36);
|
||||
b.Property(t => t.TokenType).HasConversion<EnumCodeConverter<TokenType>>().HasMaxLength(20);
|
||||
b.Property(t => t.RevokeReason).HasConversion<EnumCodeConverter<RevokeReason>>().HasMaxLength(30);
|
||||
// Vazba jen ze závislé strany – User nemá kolekci tokenů (kap. 12.3).
|
||||
b.HasOne<User>().WithMany().HasForeignKey(t => t.UserId);
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class BuildingConfiguration : IEntityTypeConfiguration<Building>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<Building> b)
|
||||
{
|
||||
b.ToTable("building");
|
||||
b.HasKey(x => x.Id);
|
||||
b.HasIndex(x => x.Code).IsUnique();
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class IssueCategoryConfiguration : IEntityTypeConfiguration<IssueCategory>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<IssueCategory> b) => b.ToTable("issue_category");
|
||||
}
|
||||
|
||||
internal sealed class ProposalCategoryConfiguration : IEntityTypeConfiguration<ProposalCategory>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<ProposalCategory> b) => b.ToTable("proposal_category");
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using Helpdesk.Domain;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
|
||||
namespace Helpdesk.Infrastructure.Persistence;
|
||||
|
||||
/// <summary>Vyplní <c>created_at</c> u nově přidaných entit s <see cref="IHasCreatedAt"/> (kap. 12.4).</summary>
|
||||
internal sealed class CreatedAtInterceptor(TimeProvider clock) : SaveChangesInterceptor
|
||||
{
|
||||
public override InterceptionResult<int> SavingChanges(DbContextEventData eventData, InterceptionResult<int> result)
|
||||
{
|
||||
Stamp(eventData.Context);
|
||||
return result;
|
||||
}
|
||||
|
||||
public override ValueTask<InterceptionResult<int>> SavingChangesAsync(
|
||||
DbContextEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default)
|
||||
{
|
||||
Stamp(eventData.Context);
|
||||
return ValueTask.FromResult(result);
|
||||
}
|
||||
|
||||
private void Stamp(DbContext? context)
|
||||
{
|
||||
if (context is null)
|
||||
return;
|
||||
|
||||
var now = clock.GetUtcNow().UtcDateTime;
|
||||
foreach (var entry in context.ChangeTracker.Entries<IHasCreatedAt>())
|
||||
{
|
||||
if (entry.State == EntityState.Added)
|
||||
entry.Entity.CreatedAt = now;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using Helpdesk.Domain;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
|
||||
namespace Helpdesk.Infrastructure.Persistence;
|
||||
|
||||
/// <summary>Enum ↔ textový kód v DB (<c>FacilityManager</c> ↔ <c>'FACILITY_MANAGER'</c>), hodnoty hlídá CHECK omezení.</summary>
|
||||
internal sealed class EnumCodeConverter<TEnum>() : ValueConverter<TEnum, string>(
|
||||
v => v.ToCode(),
|
||||
v => EnumCode.Parse<TEnum>(v))
|
||||
where TEnum : struct, Enum;
|
||||
@@ -0,0 +1,43 @@
|
||||
using Helpdesk.Application.Abstractions;
|
||||
using Helpdesk.Domain.Auth;
|
||||
using Helpdesk.Domain.Catalogs;
|
||||
using Helpdesk.Domain.Users;
|
||||
using Helpdesk.Infrastructure.Security;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
|
||||
namespace Helpdesk.Infrastructure.Persistence;
|
||||
|
||||
/// <summary>
|
||||
/// EF Core slouží jen k mapování – schéma vytvářejí SQL migrace v <c>db/migrations</c> (kap. 12.5).
|
||||
/// Názvy sloupců jsou snake_case (EFCore.NamingConventions), tabulky jsou pojmenované explicitně.
|
||||
/// </summary>
|
||||
public sealed class HelpdeskDbContext(DbContextOptions<HelpdeskDbContext> options, FieldEncryptor encryptor)
|
||||
: DbContext(options), IAppDbContext
|
||||
{
|
||||
public DbSet<User> Users => Set<User>();
|
||||
public DbSet<AuthToken> AuthTokens => Set<AuthToken>();
|
||||
public DbSet<Building> Buildings => Set<Building>();
|
||||
public DbSet<IssueCategory> IssueCategories => Set<IssueCategory>();
|
||||
public DbSet<ProposalCategory> ProposalCategories => Set<ProposalCategory>();
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
modelBuilder.ApplyConfiguration(new UserConfiguration(encryptor));
|
||||
modelBuilder.ApplyConfiguration(new AuthTokenConfiguration());
|
||||
modelBuilder.ApplyConfiguration(new BuildingConfiguration());
|
||||
modelBuilder.ApplyConfiguration(new IssueCategoryConfiguration());
|
||||
modelBuilder.ApplyConfiguration(new ProposalCategoryConfiguration());
|
||||
}
|
||||
|
||||
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
|
||||
{
|
||||
// Všechny časy jsou v DB v UTC; při čtení jim nastavíme Kind = Utc, aby se v JSON serializovaly se "Z".
|
||||
configurationBuilder.Properties<DateTime>().HaveConversion<UtcDateTimeConverter>();
|
||||
configurationBuilder.Properties<DateTime?>().HaveConversion<UtcDateTimeConverter>();
|
||||
}
|
||||
|
||||
private sealed class UtcDateTimeConverter() : ValueConverter<DateTime, DateTime>(
|
||||
v => v.Kind == DateTimeKind.Utc ? v : v.ToUniversalTime(),
|
||||
v => DateTime.SpecifyKind(v, DateTimeKind.Utc));
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using Helpdesk.Application.Abstractions;
|
||||
|
||||
namespace Helpdesk.Infrastructure.Security;
|
||||
|
||||
/// <summary>BCrypt s work factorem 12; sůl je součástí hashe (kap. 10).</summary>
|
||||
internal sealed class BCryptPasswordHasher : IPasswordHasher
|
||||
{
|
||||
private const int WorkFactor = 12;
|
||||
|
||||
public string Hash(string password) => BCrypt.Net.BCrypt.HashPassword(password, WorkFactor);
|
||||
|
||||
public bool Verify(string password, string passwordHash) => BCrypt.Net.BCrypt.Verify(password, passwordHash);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Helpdesk.Infrastructure.Security;
|
||||
|
||||
public sealed class EncryptionOptions
|
||||
{
|
||||
public const string Section = "Encryption";
|
||||
|
||||
/// <summary>256bitový klíč v Base64 (proměnná prostředí <c>Encryption__Key</c>), nikdy není v DB ani v Gitu.</summary>
|
||||
public string Key { get; set; } = "";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Šifrování citlivých údajů AES-256-GCM (kap. 10). Uložený formát: nonce (12 B) | tag (16 B) | šifrovaný text.
|
||||
/// GCM zároveň ověřuje integritu – pozměněná data se nepodaří dešifrovat.
|
||||
/// </summary>
|
||||
public sealed class FieldEncryptor
|
||||
{
|
||||
private const int NonceSize = 12;
|
||||
private const int TagSize = 16;
|
||||
private readonly byte[] _key;
|
||||
|
||||
public FieldEncryptor(IOptions<EncryptionOptions> options)
|
||||
{
|
||||
try
|
||||
{
|
||||
_key = Convert.FromBase64String(options.Value.Key);
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
throw new InvalidOperationException("Encryption:Key musí být v Base64.");
|
||||
}
|
||||
if (_key.Length != 32)
|
||||
throw new InvalidOperationException("Encryption:Key musí mít 32 bajtů (256 bitů) v Base64.");
|
||||
|
||||
StringToCipherConverter = new ValueConverter<string?, byte[]?>(
|
||||
v => v == null ? null : Encrypt(v),
|
||||
v => v == null ? null : Decrypt(v));
|
||||
}
|
||||
|
||||
public ValueConverter<string?, byte[]?> StringToCipherConverter { get; }
|
||||
|
||||
public byte[] Encrypt(string plaintext)
|
||||
{
|
||||
var plain = Encoding.UTF8.GetBytes(plaintext);
|
||||
var output = new byte[NonceSize + TagSize + plain.Length];
|
||||
var nonce = output.AsSpan(0, NonceSize);
|
||||
RandomNumberGenerator.Fill(nonce);
|
||||
|
||||
using var aes = new AesGcm(_key, TagSize);
|
||||
aes.Encrypt(nonce, plain, output.AsSpan(NonceSize + TagSize), output.AsSpan(NonceSize, TagSize));
|
||||
return output;
|
||||
}
|
||||
|
||||
public string Decrypt(byte[] data)
|
||||
{
|
||||
if (data.Length < NonceSize + TagSize)
|
||||
throw new CryptographicException("Šifrovaná hodnota je příliš krátká.");
|
||||
|
||||
var plain = new byte[data.Length - NonceSize - TagSize];
|
||||
using var aes = new AesGcm(_key, TagSize);
|
||||
aes.Decrypt(data.AsSpan(0, NonceSize), data.AsSpan(NonceSize + TagSize), data.AsSpan(NonceSize, TagSize), plain);
|
||||
return Encoding.UTF8.GetString(plain);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using Helpdesk.Application.Abstractions;
|
||||
using Helpdesk.Domain;
|
||||
using Helpdesk.Domain.Auth;
|
||||
using Helpdesk.Domain.Users;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.IdentityModel.JsonWebTokens;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
namespace Helpdesk.Infrastructure.Security;
|
||||
|
||||
public sealed class JwtOptions
|
||||
{
|
||||
public const string Section = "Jwt";
|
||||
|
||||
public string Issuer { get; set; } = "https://helpdesk.localhost";
|
||||
|
||||
/// <summary>Podpisový klíč HS256, alespoň 32 bajtů (proměnná prostředí <c>Jwt__SigningKey</c>).</summary>
|
||||
public string SigningKey { get; set; } = "";
|
||||
|
||||
public TimeSpan AccessTokenLifetime { get; set; } = TimeSpan.FromMinutes(15);
|
||||
public TimeSpan RefreshTokenLifetime { get; set; } = TimeSpan.FromDays(14);
|
||||
public TimeSpan EmailConfirmLifetime { get; set; } = TimeSpan.FromHours(24);
|
||||
public TimeSpan PasswordResetLifetime { get; set; } = TimeSpan.FromHours(1);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Vydávání a ověřování JWT podle RFC 7519 (kap. 10.1). Druh tokenu určuje hlavička <c>typ</c>,
|
||||
/// takže token jednoho druhu nejde použít místo jiného (RFC 8725, kap. 3.11).
|
||||
/// </summary>
|
||||
public sealed class JwtTokenService(IOptions<JwtOptions> options, TimeProvider clock) : ITokenService
|
||||
{
|
||||
public const string ApiAudience = "helpdesk-api";
|
||||
public const string AuthAudience = "helpdesk-auth";
|
||||
public const string RoleClaim = "role";
|
||||
|
||||
/// <summary>Povolená odchylka hodin; výchozích 5 minut v .NET je pro 15minutový token příliš.</summary>
|
||||
public static readonly TimeSpan ClockSkew = TimeSpan.FromSeconds(30);
|
||||
|
||||
private readonly JwtOptions _options = options.Value;
|
||||
private readonly JsonWebTokenHandler _handler = new() { SetDefaultTimesOnTokenCreation = false };
|
||||
|
||||
public static string HeaderType(TokenType type) => type switch
|
||||
{
|
||||
TokenType.Access => "at+jwt", // RFC 9068
|
||||
TokenType.Refresh => "refresh+jwt",
|
||||
TokenType.EmailConfirm => "email-confirm+jwt",
|
||||
TokenType.PasswordReset => "password-reset+jwt",
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(type)),
|
||||
};
|
||||
|
||||
public static SymmetricSecurityKey CreateSigningKey(string signingKey)
|
||||
{
|
||||
var bytes = Encoding.UTF8.GetBytes(signingKey);
|
||||
if (bytes.Length < 32)
|
||||
throw new InvalidOperationException("Jwt:SigningKey musí mít alespoň 32 bajtů.");
|
||||
return new SymmetricSecurityKey(bytes);
|
||||
}
|
||||
|
||||
/// <summary>Parametry ověření (RFC 7519, kap. 7.2): jen HS256, správný typ, vydavatel, příjemce a platnost.</summary>
|
||||
public static TokenValidationParameters CreateValidationParameters(JwtOptions options, TokenType type) => new()
|
||||
{
|
||||
IssuerSigningKey = CreateSigningKey(options.SigningKey),
|
||||
ValidAlgorithms = [SecurityAlgorithms.HmacSha256],
|
||||
ValidTypes = [HeaderType(type)],
|
||||
ValidIssuer = options.Issuer,
|
||||
ValidAudience = Audience(type),
|
||||
RequireExpirationTime = true,
|
||||
RequireSignedTokens = true,
|
||||
ClockSkew = ClockSkew,
|
||||
NameClaimType = JwtRegisteredClaimNames.Sub,
|
||||
RoleClaimType = RoleClaim,
|
||||
};
|
||||
|
||||
public IssuedToken Issue(User user, TokenType type)
|
||||
{
|
||||
// DATETIME(6) i NumericDate – zaokrouhlení na celé sekundy, aby claimy a řádek v DB seděly.
|
||||
var now = clock.GetUtcNow().UtcDateTime;
|
||||
var issuedAt = new DateTime(now.Ticks - now.Ticks % TimeSpan.TicksPerSecond, DateTimeKind.Utc);
|
||||
var expiresAt = issuedAt + Lifetime(type);
|
||||
var jti = Guid.NewGuid().ToString();
|
||||
|
||||
var claims = new Dictionary<string, object>
|
||||
{
|
||||
[JwtRegisteredClaimNames.Sub] = user.Id.ToString(),
|
||||
[JwtRegisteredClaimNames.Jti] = jti,
|
||||
};
|
||||
if (type == TokenType.Access)
|
||||
claims[RoleClaim] = user.Role.ToCode();
|
||||
|
||||
var token = _handler.CreateToken(new SecurityTokenDescriptor
|
||||
{
|
||||
TokenType = HeaderType(type),
|
||||
Issuer = _options.Issuer,
|
||||
Audience = Audience(type),
|
||||
IssuedAt = issuedAt,
|
||||
Expires = expiresAt,
|
||||
Claims = claims,
|
||||
SigningCredentials = new SigningCredentials(CreateSigningKey(_options.SigningKey), SecurityAlgorithms.HmacSha256),
|
||||
});
|
||||
|
||||
return new IssuedToken(token, new AuthToken(jti, user.Id, type, issuedAt, expiresAt));
|
||||
}
|
||||
|
||||
public async Task<ValidatedToken?> ValidateAsync(string token, TokenType expectedType)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(token))
|
||||
return null;
|
||||
|
||||
var parameters = CreateValidationParameters(_options, expectedType);
|
||||
parameters.LifetimeValidator = (notBefore, expires, _, p) =>
|
||||
expires is { } exp && clock.GetUtcNow().UtcDateTime <= exp.ToUniversalTime() + p.ClockSkew;
|
||||
|
||||
var result = await _handler.ValidateTokenAsync(token, parameters);
|
||||
if (!result.IsValid || result.SecurityToken is not JsonWebToken jwt)
|
||||
return null;
|
||||
|
||||
return int.TryParse(jwt.Subject, out var userId) && !string.IsNullOrEmpty(jwt.Id)
|
||||
? new ValidatedToken(jwt.Id, userId)
|
||||
: null;
|
||||
}
|
||||
|
||||
private static string Audience(TokenType type) => type == TokenType.Access ? ApiAudience : AuthAudience;
|
||||
|
||||
private TimeSpan Lifetime(TokenType type) => type switch
|
||||
{
|
||||
TokenType.Access => _options.AccessTokenLifetime,
|
||||
TokenType.Refresh => _options.RefreshTokenLifetime,
|
||||
TokenType.EmailConfirm => _options.EmailConfirmLifetime,
|
||||
TokenType.PasswordReset => _options.PasswordResetLifetime,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(type)),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
using System.Collections.Concurrent;
|
||||
using Helpdesk.Application.Abstractions;
|
||||
using Helpdesk.Domain.Auth;
|
||||
using Helpdesk.Infrastructure.Persistence;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
|
||||
namespace Helpdesk.Infrastructure.Security;
|
||||
|
||||
/// <summary>
|
||||
/// Zneplatněné access tokeny, které ještě nevypršely (kap. 10.1). Kontrola při každém požadavku
|
||||
/// tak nejde do DB. Prošlé záznamy se průběžně odstraňují – prošlý token odmítne už kontrola <c>exp</c>.
|
||||
/// API běží v jedné instanci; při více instancích by se nahradila sdílenou cache (Redis).
|
||||
/// </summary>
|
||||
internal sealed class RevokedTokenStore(TimeProvider clock) : IRevokedTokenStore
|
||||
{
|
||||
private readonly ConcurrentDictionary<string, DateTime> _revoked = new();
|
||||
private long _lastPruneTicks;
|
||||
|
||||
public bool IsRevoked(string jti)
|
||||
{
|
||||
PruneOccasionally();
|
||||
return _revoked.ContainsKey(jti);
|
||||
}
|
||||
|
||||
public void Add(string jti, DateTime expiresAt)
|
||||
{
|
||||
if (expiresAt > clock.GetUtcNow().UtcDateTime)
|
||||
_revoked[jti] = expiresAt;
|
||||
}
|
||||
|
||||
private void PruneOccasionally()
|
||||
{
|
||||
var now = clock.GetUtcNow().UtcDateTime;
|
||||
var last = Interlocked.Read(ref _lastPruneTicks);
|
||||
if (now.Ticks - last < TimeSpan.TicksPerMinute || Interlocked.CompareExchange(ref _lastPruneTicks, now.Ticks, last) != last)
|
||||
return;
|
||||
|
||||
foreach (var (jti, expiresAt) in _revoked)
|
||||
{
|
||||
if (expiresAt <= now)
|
||||
_revoked.TryRemove(jti, out _);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Při startu API načte z DB zneplatněné access tokeny, které ještě platí.</summary>
|
||||
internal sealed class RevokedTokenStoreLoader(IServiceScopeFactory scopes, IRevokedTokenStore store, TimeProvider clock) : IHostedService
|
||||
{
|
||||
public async Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
using var scope = scopes.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||
var now = clock.GetUtcNow().UtcDateTime;
|
||||
|
||||
var revoked = await db.AuthTokens.AsNoTracking()
|
||||
.Where(t => t.TokenType == TokenType.Access && t.RevokedAt != null && t.ExpiresAt > now)
|
||||
.Select(t => new { t.Jti, t.ExpiresAt })
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
foreach (var token in revoked)
|
||||
store.Add(token.Jti, token.ExpiresAt);
|
||||
}
|
||||
|
||||
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
|
||||
}
|
||||
Reference in new issue
Block a user