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.

89 lines
2.8 KiB
C#

2 months ago
using DS.Module.Core.Extensions;
12 months ago
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;
}
2 months ago
public string UserId => GetClaimValueByType("jti").FirstOrDefault() ?? "90001";
public string UserName => GetClaimValueByType("UserName").FirstOrDefault() ?? "IUser获取UserName意外为空";
public string TenantId => GetClaimValueByType("TenantId").FirstOrDefault() ?? "90002";
public string TenantName => GetClaimValueByType("TenantName").FirstOrDefault() ?? "IUser获取TenantName意外为空";
public long OrgId => GetClaimValueByType("OrgId").FirstOrDefault()?.ObjToLong() ?? 90003;
12 months ago
12 months ago
2 months ago
public List<string> GetClaimValueByType(string claimType)
{
2 months ago
return Claims.Where(x => x.Type == claimType).Select(x => x.Value).ToList();
}
2 months ago
private List<Claim>? _claims;
public List<Claim> Claims
{
get
{
2 months ago
if (_claims == null || _claims.Count == 0)
{
2 months ago
_claims = GetClaimsIdentity().ToList();
}
2 months ago
return _claims;
}
}
4 months ago
2 months ago
IEnumerable<Claim> GetClaimsIdentity()
12 months ago
{
2 months ago
if (_accessor.HttpContext == null) return ArraySegment<Claim>.Empty;
2 months ago
if (!IsAuthenticated())
{
2 months ago
var token = GetToken();
2 months ago
var jwtHandler = new JwtSecurityTokenHandler();
if (token.IsNotEmptyOrNull() && jwtHandler.CanReadToken(token))
{
2 months ago
JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token);
return jwtToken.Claims;
}
}
2 months ago
var claims = _accessor.HttpContext.User.Claims.ToList() ?? [];
12 months ago
2 months ago
// 如果有从Claims中获取HttpHeader的需求把这里放开
//var headers = _accessor.HttpContext.Request.Headers;
//foreach (var header in headers)
//{
// claims.Add(new Claim(header.Key, header.Value));
//}
return claims;
}
2 months ago
public bool IsAuthenticated()
12 months ago
{
2 months ago
return _accessor.HttpContext?.User?.Identity?.IsAuthenticated ?? false;
12 months ago
}
public string GetToken()
{
2 months ago
var token = _accessor.HttpContext?.Request?.Headers["Authorization"].ObjToString().Replace("Bearer ", "");
if (!string.IsNullOrWhiteSpace(token))
{
2 months ago
return token;
}
2 months ago
return "IUser通过GetToken()获取Token意外为空";
2 months ago
//有需要再返回
//return _accessor.HttpContext?.Request.Headers["X-Token"].FirstOrDefault()
// ?? _accessor.HttpContext?.Request.Query["Token"].FirstOrDefault()
// ?? _accessor.HttpContext?.Request.Cookies["Token"]
// ?? "东胜软件";
}
12 months ago
}