67 lines
1.4 KiB
C#
67 lines
1.4 KiB
C#
using Microsoft.AspNetCore.Http;
|
|
using System.Globalization;
|
|
using System.Security.Claims;
|
|
|
|
namespace MAX.Framework.Security;
|
|
|
|
/// <summary>
|
|
/// 从 <see cref="IHttpContextAccessor"/> 读取当前请求认证票据的默认实现。
|
|
/// </summary>
|
|
public class CurrentUser : ICurrentUser
|
|
{
|
|
private readonly IHttpContextAccessor _httpContextAccessor;
|
|
|
|
public CurrentUser(IHttpContextAccessor httpContextAccessor)
|
|
{
|
|
_httpContextAccessor = httpContextAccessor;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 当前请求的 <see cref="ClaimsPrincipal"/>
|
|
/// </summary>
|
|
private ClaimsPrincipal? Principal => _httpContextAccessor.HttpContext?.User;
|
|
|
|
/// <inheritdoc />
|
|
public bool IsAuthenticated => Principal?.Identity?.IsAuthenticated == true;
|
|
|
|
/// <inheritdoc />
|
|
public string? UserName => GetClaimValue(JwtClaimTypes.UserName);
|
|
|
|
/// <inheritdoc />
|
|
public string? NickName => GetClaimValue(JwtClaimTypes.NickName);
|
|
|
|
/// <inheritdoc />
|
|
public IEnumerable<Claim> Claims => Principal?.Claims ?? [];
|
|
|
|
/// <inheritdoc />
|
|
public string? GetClaimValue(string claimType)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(claimType))
|
|
{
|
|
return null;
|
|
}
|
|
|
|
return Principal?.FindFirst(claimType)?.Value;
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public T? GetClaimValue<T>(string claimType)
|
|
{
|
|
string? value = GetClaimValue(claimType);
|
|
if (value is null)
|
|
{
|
|
return default;
|
|
}
|
|
|
|
try
|
|
{
|
|
return (T)Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCulture);
|
|
}
|
|
catch
|
|
{
|
|
return default;
|
|
}
|
|
}
|
|
}
|
|
|