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,80 @@
|
||||
using System.Globalization;
|
||||
using System.Security.Claims;
|
||||
using Helpdesk.Web.Api;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
|
||||
namespace Helpdesk.Web.Auth;
|
||||
|
||||
/// <summary>
|
||||
/// Autentizační cookie webu (kap. 9.4): identita uživatele pro Razor a tokeny pro volání API.
|
||||
/// Cookie je HttpOnly a šifrovaná přes Data Protection – tokeny nejsou dostupné JavaScriptu.
|
||||
/// </summary>
|
||||
public static class AuthCookie
|
||||
{
|
||||
public const string Name = "ntbug.auth";
|
||||
public const string AccessToken = "access_token";
|
||||
public const string AccessTokenExpiresAt = "access_token_expires_at";
|
||||
public const string RefreshToken = "refresh_token";
|
||||
public const string RefreshTokenExpiresAt = "refresh_token_expires_at";
|
||||
|
||||
public static async Task SignInAsync(HttpContext httpContext, AuthResponse auth, bool persistent)
|
||||
{
|
||||
var properties = new AuthenticationProperties { IsPersistent = persistent };
|
||||
StoreTokens(properties, auth.Tokens);
|
||||
await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, CreatePrincipal(auth.User), properties);
|
||||
}
|
||||
|
||||
/// <summary>Přepíše identitu v cookie (např. po změně jména v profilu); tokeny zůstanou.</summary>
|
||||
public static async Task UpdateUserAsync(HttpContext httpContext, UserDto user)
|
||||
{
|
||||
var result = await httpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
|
||||
if (result.Succeeded)
|
||||
await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, CreatePrincipal(user), result.Properties);
|
||||
}
|
||||
|
||||
public static ClaimsPrincipal CreatePrincipal(UserDto user)
|
||||
{
|
||||
var identity = new ClaimsIdentity(
|
||||
[
|
||||
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString(CultureInfo.InvariantCulture)),
|
||||
new Claim(ClaimTypes.Name, user.FullName),
|
||||
new Claim(ClaimTypes.Email, user.Email),
|
||||
new Claim(ClaimTypes.Role, user.Role),
|
||||
],
|
||||
CookieAuthenticationDefaults.AuthenticationScheme);
|
||||
return new ClaimsPrincipal(identity);
|
||||
}
|
||||
|
||||
public static void StoreTokens(AuthenticationProperties properties, TokenSet tokens)
|
||||
{
|
||||
properties.StoreTokens(
|
||||
[
|
||||
new AuthenticationToken { Name = AccessToken, Value = tokens.AccessToken },
|
||||
new AuthenticationToken { Name = AccessTokenExpiresAt, Value = tokens.AccessTokenExpiresAt.ToString("O", CultureInfo.InvariantCulture) },
|
||||
new AuthenticationToken { Name = RefreshToken, Value = tokens.RefreshToken },
|
||||
new AuthenticationToken { Name = RefreshTokenExpiresAt, Value = tokens.RefreshTokenExpiresAt.ToString("O", CultureInfo.InvariantCulture) },
|
||||
]);
|
||||
|
||||
// Trvalé přihlášení („zůstat přihlášen“) platí stejně dlouho jako refresh token.
|
||||
if (properties.IsPersistent)
|
||||
properties.ExpiresUtc = tokens.RefreshTokenExpiresAt;
|
||||
}
|
||||
|
||||
public static TokenSet? ReadTokens(AuthenticationProperties properties)
|
||||
{
|
||||
var access = properties.GetTokenValue(AccessToken);
|
||||
var refresh = properties.GetTokenValue(RefreshToken);
|
||||
if (string.IsNullOrEmpty(access) || string.IsNullOrEmpty(refresh) ||
|
||||
!TryParse(properties.GetTokenValue(AccessTokenExpiresAt), out var accessExpires) ||
|
||||
!TryParse(properties.GetTokenValue(RefreshTokenExpiresAt), out var refreshExpires))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new TokenSet(access, accessExpires, refresh, refreshExpires);
|
||||
}
|
||||
|
||||
private static bool TryParse(string? value, out DateTimeOffset result) =>
|
||||
DateTimeOffset.TryParse(value, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out result);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
using Helpdesk.Web.Api;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
|
||||
namespace Helpdesk.Web.Auth;
|
||||
|
||||
/// <summary>
|
||||
/// Při každém požadavku zkontroluje tokeny v cookie. Access token (15 min) obnoví chvíli před
|
||||
/// vypršením, takže volání API během požadavku už má platný token. Když API refresh token
|
||||
/// odmítne (odhlášení jinde, změna role, změna hesla), uživatele odhlásí.
|
||||
/// </summary>
|
||||
public sealed partial class HelpdeskCookieEvents(
|
||||
TokenRefresher refresher,
|
||||
AuthApiClient authApi,
|
||||
TimeProvider clock,
|
||||
ILogger<HelpdeskCookieEvents> logger) : CookieAuthenticationEvents
|
||||
{
|
||||
/// <summary>Jak dlouho před vypršením se access token obnoví.</summary>
|
||||
internal static readonly TimeSpan RefreshMargin = TimeSpan.FromMinutes(1);
|
||||
|
||||
public override async Task ValidatePrincipal(CookieValidatePrincipalContext context)
|
||||
{
|
||||
var tokens = context.Properties is { } properties ? AuthCookie.ReadTokens(properties) : null;
|
||||
var now = clock.GetUtcNow();
|
||||
|
||||
if (tokens is null || tokens.RefreshTokenExpiresAt <= now)
|
||||
{
|
||||
await RejectAsync(context);
|
||||
return;
|
||||
}
|
||||
|
||||
if (tokens.AccessTokenExpiresAt - now > RefreshMargin)
|
||||
return;
|
||||
|
||||
TokenSet? renewed;
|
||||
try
|
||||
{
|
||||
// Sdílené volání nesmí zrušit odpojení prvního klienta – ostatní na výsledek čekají také.
|
||||
renewed = await refresher.RefreshAsync(tokens.RefreshToken, token => authApi.RefreshAsync(token, CancellationToken.None));
|
||||
}
|
||||
catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or ApiException)
|
||||
{
|
||||
// API je dočasně nedostupné. Uživatele kvůli výpadku neodhlašujeme; požadavek
|
||||
// dopadne chybovou stránkou a příští pokus obnovu zopakuje.
|
||||
LogRefreshFailed(ex);
|
||||
return;
|
||||
}
|
||||
|
||||
if (renewed is null)
|
||||
{
|
||||
await RejectAsync(context);
|
||||
return;
|
||||
}
|
||||
|
||||
AuthCookie.StoreTokens(context.Properties!, renewed);
|
||||
context.ShouldRenew = true;
|
||||
}
|
||||
|
||||
private static async Task RejectAsync(CookieValidatePrincipalContext context)
|
||||
{
|
||||
context.RejectPrincipal();
|
||||
await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
|
||||
}
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Warning, Message = "Obnova access tokenu selhala, API je nedostupné.")]
|
||||
private partial void LogRefreshFailed(Exception ex);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Helpdesk.Web.Api;
|
||||
|
||||
namespace Helpdesk.Web.Auth;
|
||||
|
||||
/// <summary>
|
||||
/// Sloučí souběžné obnovy téhož refresh tokenu do jednoho volání API.
|
||||
/// <para>
|
||||
/// Refresh token jde použít jen jednou a druhé použití API vyhodnotí jako krádež – zneplatní
|
||||
/// všechny tokeny uživatele (kap. 10.1). Prohlížeč přitom běžně pošle několik požadavků naráz
|
||||
/// se stejnou cookie. Všechny proto čekají na jedno volání a dostanou stejný nový pár tokenů;
|
||||
/// výsledek se drží ještě chvíli pro požadavky, které dorazí se starou cookie o něco později.
|
||||
/// </para>
|
||||
/// Platí pro jednu instanci webu; při více instancích by se evidence přesunula do sdílené cache.
|
||||
/// </summary>
|
||||
public sealed class TokenRefresher(TimeProvider clock)
|
||||
{
|
||||
internal static readonly TimeSpan ResultLifetime = TimeSpan.FromMinutes(1);
|
||||
|
||||
private readonly ConcurrentDictionary<string, Entry> _refreshes = new();
|
||||
|
||||
/// <param name="refreshToken">Refresh token z cookie.</param>
|
||||
/// <param name="refresh">Skutečné volání API; spustí se nejvýše jednou pro daný token.</param>
|
||||
/// <returns>Nový pár tokenů, nebo <c>null</c>, když API token odmítlo.</returns>
|
||||
public async Task<TokenSet?> RefreshAsync(string refreshToken, Func<string, Task<TokenSet?>> refresh)
|
||||
{
|
||||
RemoveExpired();
|
||||
|
||||
var key = Hash(refreshToken);
|
||||
var entry = _refreshes.GetOrAdd(key, _ => new Entry(
|
||||
new Lazy<Task<TokenSet?>>(() => refresh(refreshToken)),
|
||||
clock.GetUtcNow()));
|
||||
|
||||
try
|
||||
{
|
||||
return await entry.Result.Value;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Dočasná chyba (API nedostupné) se nepamatuje – další požadavek to zkusí znovu.
|
||||
_refreshes.TryRemove(new KeyValuePair<string, Entry>(key, entry));
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private void RemoveExpired()
|
||||
{
|
||||
var threshold = clock.GetUtcNow() - ResultLifetime;
|
||||
foreach (var (key, entry) in _refreshes)
|
||||
{
|
||||
if (entry.CreatedAt < threshold && entry.Result.IsValueCreated && entry.Result.Value.IsCompleted)
|
||||
_refreshes.TryRemove(new KeyValuePair<string, Entry>(key, entry));
|
||||
}
|
||||
}
|
||||
|
||||
// Klíčem je hash, aby se refresh tokeny nedržely v paměti jako klíče slovníku.
|
||||
private static string Hash(string token) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(token)));
|
||||
|
||||
private sealed record Entry(Lazy<Task<TokenSet?>> Result, DateTimeOffset CreatedAt);
|
||||
}
|
||||
Reference in new issue
Block a user