43 lines
1.2 KiB
C#
43 lines
1.2 KiB
C#
using System.Security.Claims;
|
|
using Microsoft.AspNetCore.Http;
|
|
using TakeoutSaaS.Shared.Abstractions.Security;
|
|
|
|
namespace TakeoutSaaS.Shared.Web.Security;
|
|
|
|
/// <summary>
|
|
/// 基于 HttpContext 的当前用户访问器。
|
|
/// </summary>
|
|
public sealed class HttpContextCurrentUserAccessor : ICurrentUserAccessor
|
|
{
|
|
private readonly IHttpContextAccessor _httpContextAccessor;
|
|
|
|
/// <summary>
|
|
/// 初始化访问器。
|
|
/// </summary>
|
|
public HttpContextCurrentUserAccessor(IHttpContextAccessor httpContextAccessor)
|
|
{
|
|
_httpContextAccessor = httpContextAccessor;
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public Guid UserId
|
|
{
|
|
get
|
|
{
|
|
var principal = _httpContextAccessor.HttpContext?.User;
|
|
if (principal == null || !principal.Identity?.IsAuthenticated == true)
|
|
{
|
|
return Guid.Empty;
|
|
}
|
|
|
|
var identifier = principal.FindFirstValue(ClaimTypes.NameIdentifier)
|
|
?? principal.FindFirstValue("sub");
|
|
|
|
return Guid.TryParse(identifier, out var id) ? id : Guid.Empty;
|
|
}
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public bool IsAuthenticated => UserId != Guid.Empty;
|
|
}
|