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
81 lines
3.7 KiB
C#
81 lines
3.7 KiB
C#
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);
|
||
}
|