web: přihlášení přes API a automatická obnova tokenů
Typovaný klient REST API, tokeny v šifrované HttpOnly cookie, obnova access tokenu před vypršením se sloučením souběžných obnov (ochrana proti REUSE_DETECTED), odhlášení a společné zpracování chyb API. Refs #21
This commit is contained in:
1 parent
abd075287c
commit
d3a1b1cb17
22 files changed
+697
-1
No files matched your search
@@ -0,0 +1,71 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Helpdesk.Web.Api;
|
||||
|
||||
/// <summary>
|
||||
/// Neúspěšná odpověď API ve formátu ProblemDetails (RFC 9457). Nese stav, titulek
|
||||
/// a u validačních chyb seznam chyb podle polí (klíče jsou názvy vlastností v camelCase).
|
||||
/// </summary>
|
||||
public sealed class ApiException(HttpStatusCode statusCode, string? title, IReadOnlyDictionary<string, string[]> errors)
|
||||
: Exception(title ?? $"API vrátilo stav {(int)statusCode}.")
|
||||
{
|
||||
public HttpStatusCode StatusCode { get; } = statusCode;
|
||||
public string? Title { get; } = title;
|
||||
public IReadOnlyDictionary<string, string[]> Errors { get; } = errors;
|
||||
|
||||
/// <summary>Text pro uživatele. API píše titulky chyb česky, kromě odpovědí bez těla (např. 429).</summary>
|
||||
public string UserMessage => StatusCode switch
|
||||
{
|
||||
HttpStatusCode.TooManyRequests => "Příliš mnoho pokusů. Zkuste to prosím za minutu.",
|
||||
_ when !string.IsNullOrWhiteSpace(Title) => Title,
|
||||
HttpStatusCode.Forbidden => "K této akci nemáte oprávnění.",
|
||||
HttpStatusCode.NotFound => "Záznam nebyl nalezen.",
|
||||
_ => "Požadavek se nepodařilo zpracovat. Zkuste to prosím znovu.",
|
||||
};
|
||||
|
||||
public static async Task<ApiException> FromResponseAsync(HttpResponseMessage response, CancellationToken ct)
|
||||
{
|
||||
string? title = null;
|
||||
Dictionary<string, string[]> errors = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
if (response.Content.Headers.ContentType?.MediaType is { } mediaType && mediaType.Contains("json", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
try
|
||||
{
|
||||
var problem = await response.Content.ReadFromJsonAsync<ProblemBody>(ct);
|
||||
title = problem?.Title;
|
||||
if (problem?.Errors is { } fieldErrors)
|
||||
{
|
||||
foreach (var (field, messages) in fieldErrors)
|
||||
errors[field] = messages;
|
||||
}
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
// Tělo není ProblemDetails – zůstane jen stavový kód.
|
||||
}
|
||||
}
|
||||
|
||||
return new ApiException(response.StatusCode, title, errors);
|
||||
}
|
||||
|
||||
private sealed record ProblemBody(string? Title, Dictionary<string, string[]>? Errors);
|
||||
}
|
||||
|
||||
internal static class ApiResponse
|
||||
{
|
||||
public static async Task EnsureSuccessAsync(HttpResponseMessage response, CancellationToken ct)
|
||||
{
|
||||
if (!response.IsSuccessStatusCode)
|
||||
throw await ApiException.FromResponseAsync(response, ct);
|
||||
}
|
||||
|
||||
public static async Task<T> ReadAsync<T>(HttpResponseMessage response, CancellationToken ct)
|
||||
{
|
||||
await EnsureSuccessAsync(response, ct);
|
||||
return await response.Content.ReadFromJsonAsync<T>(ct)
|
||||
?? throw new InvalidOperationException($"API vrátilo prázdnou odpověď místo {typeof(T).Name}.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
namespace Helpdesk.Web.Api;
|
||||
|
||||
// Kontrakt REST API /api/v1 tak, jak ho web používá. Web je tenký klient a na projekty
|
||||
// backendu nemá referenci – DTO jsou zde zrcadlem dokumentace ve Swaggeru.
|
||||
|
||||
public sealed record UserDto(
|
||||
int Id,
|
||||
string Email,
|
||||
string FirstName,
|
||||
string LastName,
|
||||
string? Phone,
|
||||
string Role,
|
||||
bool EmailNotificationsEnabled)
|
||||
{
|
||||
public string FullName => $"{FirstName} {LastName}";
|
||||
}
|
||||
|
||||
public sealed record AuthResponse(
|
||||
string AccessToken,
|
||||
DateTimeOffset AccessTokenExpiresAt,
|
||||
string RefreshToken,
|
||||
DateTimeOffset RefreshTokenExpiresAt,
|
||||
UserDto User)
|
||||
{
|
||||
public TokenSet Tokens => new(AccessToken, AccessTokenExpiresAt, RefreshToken, RefreshTokenExpiresAt);
|
||||
}
|
||||
|
||||
/// <summary>Pár tokenů uložený v autentizační cookie webu.</summary>
|
||||
public sealed record TokenSet(
|
||||
string AccessToken,
|
||||
DateTimeOffset AccessTokenExpiresAt,
|
||||
string RefreshToken,
|
||||
DateTimeOffset RefreshTokenExpiresAt);
|
||||
|
||||
public sealed record LoginRequest(string Email, string Password);
|
||||
|
||||
public sealed record RegisterRequest(string Email, string Password, string FirstName, string LastName);
|
||||
|
||||
public sealed record RefreshTokenRequest(string RefreshToken);
|
||||
|
||||
public sealed record EmailTokenRequest(string Token);
|
||||
|
||||
public sealed record ForgotPasswordRequest(string Email);
|
||||
|
||||
public sealed record ResetPasswordRequest(string Token, string NewPassword);
|
||||
|
||||
public sealed record UpdateProfileRequest(string FirstName, string LastName, string? Phone, bool EmailNotificationsEnabled);
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace Helpdesk.Web.Api;
|
||||
|
||||
/// <summary>Připojení k backendu (sekce <c>Api</c>). V Dockeru <c>http://api:8080/</c>.</summary>
|
||||
public sealed class ApiOptions
|
||||
{
|
||||
public const string Section = "Api";
|
||||
|
||||
public string BaseUrl { get; set; } = "";
|
||||
|
||||
public TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds(15);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
|
||||
namespace Helpdesk.Web.Api;
|
||||
|
||||
/// <summary>
|
||||
/// Anonymní endpointy <c>/api/v1/auth</c>. Záměrně bez <see cref="BearerTokenHandler"/>:
|
||||
/// obnova tokenu běží uvnitř ověřování cookie a čtení tokenu z cookie by se zacyklilo.
|
||||
/// </summary>
|
||||
public sealed class AuthApiClient(HttpClient http)
|
||||
{
|
||||
public async Task<AuthResponse> LoginAsync(LoginRequest request, CancellationToken ct)
|
||||
{
|
||||
using var response = await http.PostAsJsonAsync("api/v1/auth/login", request, ct);
|
||||
return await ApiResponse.ReadAsync<AuthResponse>(response, ct);
|
||||
}
|
||||
|
||||
/// <summary>Obnoví pár tokenů. Neplatný nebo už použitý refresh token → <c>null</c>.</summary>
|
||||
public async Task<TokenSet?> RefreshAsync(string refreshToken, CancellationToken ct)
|
||||
{
|
||||
using var response = await http.PostAsJsonAsync("api/v1/auth/refresh", new RefreshTokenRequest(refreshToken), ct);
|
||||
if (response.StatusCode == HttpStatusCode.Unauthorized)
|
||||
return null;
|
||||
return (await ApiResponse.ReadAsync<AuthResponse>(response, ct)).Tokens;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
using System.Net.Http.Headers;
|
||||
using Helpdesk.Web.Auth;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
|
||||
namespace Helpdesk.Web.Api;
|
||||
|
||||
/// <summary>
|
||||
/// Přidá k požadavku na API access token přihlášeného uživatele z autentizační cookie.
|
||||
/// Token je v té chvíli čerstvý – případnou obnovu už provedl <see cref="HelpdeskCookieEvents"/>.
|
||||
/// </summary>
|
||||
internal sealed class BearerTokenHandler(IHttpContextAccessor accessor) : DelegatingHandler
|
||||
{
|
||||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (accessor.HttpContext is { } httpContext &&
|
||||
await httpContext.GetTokenAsync(AuthCookie.AccessToken) is { Length: > 0 } token)
|
||||
{
|
||||
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||
}
|
||||
|
||||
return await base.SendAsync(request, cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using System.Net.Http.Json;
|
||||
|
||||
namespace Helpdesk.Web.Api;
|
||||
|
||||
/// <summary>Endpointy API pro přihlášeného uživatele; access token přidává <see cref="BearerTokenHandler"/>.</summary>
|
||||
public sealed class HelpdeskApiClient(HttpClient http)
|
||||
{
|
||||
/// <summary>Odhlásí toto zařízení – API zneplatní aktuální access token i předaný refresh token.</summary>
|
||||
public async Task LogoutAsync(string refreshToken, CancellationToken ct)
|
||||
{
|
||||
using var response = await http.PostAsJsonAsync("api/v1/auth/logout", new RefreshTokenRequest(refreshToken), ct);
|
||||
await ApiResponse.EnsureSuccessAsync(response, ct);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user