67 lines
2.5 KiB
C#
67 lines
2.5 KiB
C#
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);
|
|||
|
|
}
|