Files
NTBug/web/Helpdesk.Web/Auth/AuthCookie.cs
PatTheEvil d3a1b1cb17 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
2026-12-02 00:26:42 +01:00

81 lines
3.7 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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);
}