You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
80 lines
2.4 KiB
C#
80 lines
2.4 KiB
C#
using DS.Module.Core.Extensions;
|
|
using Microsoft.AspNetCore.Http;
|
|
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Security.Claims;
|
|
|
|
namespace DS.Module.UserModule;
|
|
|
|
public class AspNetUser : IUser
|
|
{
|
|
private readonly IHttpContextAccessor _accessor;
|
|
|
|
public AspNetUser(IHttpContextAccessor accessor)
|
|
{
|
|
_accessor = accessor;
|
|
}
|
|
|
|
public string UserId => GetClaimValueByType("jti") ?? "90001";
|
|
public string UserName => GetClaimValueByType("UserName") ?? "IUser获取UserName意外为空";
|
|
public string TenantId => GetClaimValueByType("TenantId") ?? "90002";
|
|
public string TenantName => GetClaimValueByType("TenantName") ?? "IUser获取TenantName意外为空";
|
|
public long OrgId => GetClaimValueByType("OrgId")?.ObjToLong() ?? 90003;
|
|
|
|
|
|
|
|
|
|
public string? GetClaimValueByType(string claimType)
|
|
{
|
|
return Claims.Where(x => x.Type == claimType).Select(x => x.Value).FirstOrDefault();
|
|
}
|
|
|
|
private List<Claim>? _claims;
|
|
public List<Claim> Claims
|
|
{
|
|
get
|
|
{
|
|
if (_claims == null || _claims.Count == 0)
|
|
{
|
|
_claims = GetClaimsIdentity().ToList();
|
|
}
|
|
return _claims;
|
|
}
|
|
}
|
|
|
|
IEnumerable<Claim> GetClaimsIdentity()
|
|
{
|
|
if (_accessor.HttpContext == null) return ArraySegment<Claim>.Empty;
|
|
|
|
var token = GetToken();
|
|
|
|
var jwtHandler = new JwtSecurityTokenHandler();
|
|
if (token.IsNotEmptyOrNull() && jwtHandler.CanReadToken(token))
|
|
{
|
|
JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token);
|
|
return jwtToken.Claims;
|
|
}
|
|
else
|
|
{
|
|
return ArraySegment<Claim>.Empty;
|
|
}
|
|
}
|
|
public bool IsAuthenticated()
|
|
{
|
|
return _accessor.HttpContext?.User?.Identity?.IsAuthenticated ?? false;
|
|
}
|
|
public string GetToken()
|
|
{
|
|
var token = _accessor.HttpContext?.Request?.Headers["Authorization"].ObjToString().Replace("Bearer ", "");
|
|
if (!string.IsNullOrWhiteSpace(token))
|
|
{
|
|
return token;
|
|
}
|
|
return "IUser通过GetToken()获取Token意外为空";
|
|
|
|
//有需要再返回
|
|
//return _accessor.HttpContext?.Request.Headers["X-Token"].FirstOrDefault()
|
|
// ?? _accessor.HttpContext?.Request.Query["Token"].FirstOrDefault()
|
|
// ?? _accessor.HttpContext?.Request.Cookies["Token"]
|
|
// ?? "东胜软件";
|
|
}
|
|
} |