添加项目文件。
This commit is contained in:
1 parent
6a017c9547
commit
58abbb5b4f
86 files changed
+8729
No files matched your search
@@ -0,0 +1,76 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.Globalization;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace StoreHub.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 int? Id
|
||||
{
|
||||
get
|
||||
{
|
||||
string? value = GetClaimValue(JwtClaimTypes.UserId);
|
||||
return int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int id) ? id : null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user