Files
mtusi2026lab2/scr/Messenger.Api/Services/BearerAuth.cs
T
2026-10-23 21:13:27 +03:00

92 lines
3.5 KiB
C#

using System.Security.Claims;
using System.Text.Encodings.Web;
using Messenger.Api.Data;
using Microsoft.AspNetCore.Authentication;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
namespace Messenger.Api.Services;
public static class BearerAuth
{
public const string Scheme = "Bearer";
public const string Challenge = "Bearer realm=\"messenger\"";
public const string SessionIdClaim = "session_id";
// Ровно один заголовок Authorization вида "Bearer <token>"; иначе null (Basic и прочее здесь не принимаются).
public static string? ExtractToken(HttpRequest request)
{
if (request.Headers.Authorization.Count != 1)
{
return null;
}
var value = request.Headers.Authorization[0];
const string prefix = "Bearer ";
if (value is null || !value.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
{
return null;
}
var token = value[prefix.Length..].Trim();
return token.Length == 0 ? null : token;
}
public static Guid GetUserId(this HttpContext context) =>
Guid.Parse(context.User.FindFirstValue(ClaimTypes.NameIdentifier)!);
public static Guid GetSessionId(this HttpContext context) =>
Guid.Parse(context.User.FindFirstValue(SessionIdClaim)!);
}
// Стандартный обработчик аутентификации ASP.NET: превращает Bearer-токен в ClaimsPrincipal.
// Срабатывает до выбора и выполнения эндпоинта (в том числе до разбора тела), поэтому 401 всегда раньше 400/404.
public sealed class SessionAuthenticationHandler(
IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
MessengerDbContext db)
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
{
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
var token = BearerAuth.ExtractToken(Request);
if (token is null)
{
return AuthenticateResult.NoResult();
}
var hash = SessionTokens.Hash(token);
var now = Timestamps.UtcNowMilliseconds();
// Неизвестный, истёкший и отозванный токен неразличимы для клиента: во всех случаях это один 401.
var session = await db.Sessions
.AsNoTracking()
.Where(s => s.TokenHash == hash && s.RevokedAt == null && s.ExpiresAt > now)
.Select(s => new { s.Id, s.UserId })
.FirstOrDefaultAsync(Context.RequestAborted);
if (session is null)
{
return AuthenticateResult.Fail("Недействительная сессия");
}
var identity = new ClaimsIdentity(
[
new Claim(ClaimTypes.NameIdentifier, session.UserId.ToString()),
new Claim(BearerAuth.SessionIdClaim, session.Id.ToString())
],
BearerAuth.Scheme);
return AuthenticateResult.Success(
new AuthenticationTicket(new ClaimsPrincipal(identity), BearerAuth.Scheme));
}
protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
{
await ApiErrors
.Unauthorized(Context, BearerAuth.Challenge, "Требуется действительный Bearer-токен")
.ExecuteAsync(Context);
}
}