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.

423 lines
13 KiB
C#

12 months ago
using DS.Module.Core;
using DS.Module.Core.Extensions;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
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 UserInfo UserInfo => GetUserInfo();
//public string GetToken()
//{
// return _accessor.HttpContext?.Request?.Headers["Authorization"].ToString().Replace("Bearer ", "");
//}
//public string UserId => GetClaimValueByType("jti").FirstOrDefault().ObjToString();
private string _userId;
public string UserId
12 months ago
{
get
{
if (_userId == null)
{
var claimValue = GetClaimValueByType("jti").FirstOrDefault();
_userId = claimValue != null ? claimValue.ObjToString() : "1288018625843826688";
}
return _userId;
}
set
{
_userId = value;
}
12 months ago
}
private string _userName;
12 months ago
public string UserName
{
get
{
if (_userId == null)
{
var claimValue = GetClaimValueByType("Name").FirstOrDefault();
_userName = claimValue != null ? claimValue.ObjToString() : "管理员";
}
return _userName;
}
set
{
_userName = value;
}
}
public long GetTenantId()
12 months ago
{
var token = GetToken();
if (string.IsNullOrEmpty(token))
12 months ago
{
return 0;
}
12 months ago
var jwtHandler = new JwtSecurityTokenHandler();
if (!jwtHandler.CanReadToken(token))
{
return 0;
12 months ago
}
10 months ago
JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token);
var tenantIdClaim = jwtToken.Claims.FirstOrDefault(x => x.Type == "TenantId");
return tenantIdClaim != null ? Convert.ToInt64(tenantIdClaim.Value) : 0;
12 months ago
}
//public long GetTenantId()
//{
// // return _accessor.HttpContext?.Request?.Headers["Authorization"].ToString().Replace("Bearer ", "");
// var tenantId = String.Empty;
// var token = _accessor.HttpContext?.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last()
// ?? _accessor.HttpContext?.Request.Headers["X-Token"].FirstOrDefault()
// ?? _accessor.HttpContext?.Request.Query["Token"].FirstOrDefault()
// ?? _accessor.HttpContext?.Request.Cookies["Token"];
// // token校验
// var jwtHandler = new JwtSecurityTokenHandler();
// if (!token.IsNullOrEmpty() && jwtHandler.CanReadToken(token))
// {
// JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token);
// tenantId = jwtToken.Claims.First(x => x.Type == "TenantId").Value;
// }
// return Convert.ToInt64(tenantId);
//}
10 months ago
public long GetOrgId()
12 months ago
{
var token = GetToken();
if (string.IsNullOrEmpty(token))
12 months ago
{
return 0;
}
12 months ago
var jwtHandler = new JwtSecurityTokenHandler();
if (!jwtHandler.CanReadToken(token))
{
return 0;
12 months ago
}
JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token);
var orgIdClaim = jwtToken.Claims.FirstOrDefault(x => x.Type == "OrgId");
return orgIdClaim != null ? Convert.ToInt64(orgIdClaim.Value) : 0;
12 months ago
}
//public long GetOrgId()
//{
// // return _accessor.HttpContext?.Request?.Headers["Authorization"].ToString().Replace("Bearer ", "");
// var orgId = String.Empty;
// var token = _accessor.HttpContext?.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last()
// ?? _accessor.HttpContext?.Request.Headers["X-Token"].FirstOrDefault()
// ?? _accessor.HttpContext?.Request.Query["Token"].FirstOrDefault()
// ?? _accessor.HttpContext?.Request.Cookies["Token"];
// // token校验
// var jwtHandler = new JwtSecurityTokenHandler();
// if (!token.IsNullOrEmpty() && jwtHandler.CanReadToken(token))
// {
// JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token);
// orgId = jwtToken.Claims.First(x => x.Type == "OrgId").Value;
// }
// return Convert.ToInt64(orgId);
//}
//public string GetCompanyId()
//{
// // return _accessor.HttpContext?.Request?.Headers["Authorization"].ToString().Replace("Bearer ", "");
// var companyId = String.Empty;
// var token = _accessor.HttpContext?.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last()
// ?? _accessor.HttpContext?.Request.Headers["X-Token"].FirstOrDefault()
// ?? _accessor.HttpContext?.Request.Query["Token"].FirstOrDefault()
// ?? _accessor.HttpContext?.Request.Cookies["Token"];
// // token校验
// var jwtHandler = new JwtSecurityTokenHandler();
// if (!token.IsNullOrEmpty() && jwtHandler.CanReadToken(token))
// {
// JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token);
// companyId = jwtToken.Claims.First(x => x.Type == "OrgId").Value;
// }
// return companyId;
//}
10 months ago
public string GetCompanyId()
12 months ago
{
var token = GetToken();
if (string.IsNullOrEmpty(token))
{
return string.Empty;
}
12 months ago
var jwtHandler = new JwtSecurityTokenHandler();
if (!jwtHandler.CanReadToken(token))
{
return string.Empty;
}
JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token);
var companyIdClaim = jwtToken.Claims.FirstOrDefault(x => x.Type == "OrgId");
return companyIdClaim?.Value ?? "0000000001";
}
//public string TenantId => GetClaimValueByType("TenantId").FirstOrDefault().ObjToString();
private string _tenantId;
public string TenantId
{
get
{
if (_tenantId == null)
{
var tenantIdClaim = GetClaimValueByType("TenantId").FirstOrDefault();
_tenantId = tenantIdClaim != null ? tenantIdClaim.ObjToString() : "00000000000001";
}
return _tenantId;
}
set
12 months ago
{
_tenantId = value;
}
}
// public string CompanyId => GetClaimValueByType("CompanyId").FirstOrDefault().ObjToString();
private string _companyId;
12 months ago
public string CompanyId
{
get
{
if (_companyId == null)
{
var companyIdClaim = GetClaimValueByType("CompanyId").FirstOrDefault();
_companyId = companyIdClaim != null ? companyIdClaim.ObjToString() : "东胜软件";
}
return _companyId;
}
set
{
_companyId = value;
12 months ago
}
}
// public string OrgId => GetClaimValueByType("OrgId").FirstOrDefault().ObjToString();
private string _orgId;
12 months ago
public string OrgId
{
get
{
if (_orgId == null)
{
var orgIdClaim = GetClaimValueByType("OrgId").FirstOrDefault();
_orgId = orgIdClaim != null ? orgIdClaim.ObjToString() : "1111111111";
}
return _orgId;
}
set
{
_orgId = value;
}
}
12 months ago
public UserInfo GetUserInfo()
{
var user = _accessor.HttpContext?.User;
if (user == null || !user.Claims.Any())
{
return null;
// return GetDefaultUserInfo();
}
var token = GetToken();
if (string.IsNullOrEmpty(token))
12 months ago
{
return null;
// return GetDefaultUserInfo();
12 months ago
}
var jwtHandler = new JwtSecurityTokenHandler();
if (!jwtHandler.CanReadToken(token))
{
return null;
// return GetDefaultUserInfo();
}
JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token);
var userInfoJson = jwtToken.Claims.First().Value;
var userInfo = JsonConvert.DeserializeObject<UserInfo>(userInfoJson);
return userInfo ?? null;
12 months ago
}
private UserInfo GetDefaultUserInfo()
{
return new UserInfo()
{
CompanyId = "000001",
CompanyName = "东胜软件",
Token = "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSm9obiIsImFkbWluIjp0cnVlfQ",
UserCode = "0000001",
UserId = "00000000",
UserName = "东胜软件",
};
}
public string GetToken()
{
if (_accessor == null || _accessor.HttpContext == null)
{
return "东胜软件";
}
var request = _accessor.HttpContext.Request;
var authorizationHeader = request.Headers["Authorization"].FirstOrDefault();
if (!string.IsNullOrEmpty(authorizationHeader))
{
return authorizationHeader.Split(" ").Last();
}
return request.Headers["X-Token"].FirstOrDefault()
?? request.Query["Token"].FirstOrDefault()
?? request.Cookies["Token"]
?? "东胜软件";
}
#region 优化前
//public string GetToken()
//{
// var headers = _accessor.HttpContext?.Request?.Headers;
// if (headers != null && headers.ContainsKey("Authorization"))
// {
// return headers["Authorization"].ToString().Replace("Bearer ", "");
// }
// return null;
//}
//public UserInfo GetUserInfo()
//{
// if (_accessor.HttpContext.User.Claims == null)
// {
// return new UserInfo()
// {
// CompanyId = "1",
// CompanyName = "初始化",
// Token = "初始化",
// UserCode = "初始化",
// UserId = "00000000",
// UserName = "初始化",
// };
// }
// //var json = _accessor.HttpContext.User.Claims;
// //获取上传token可自定义扩展
// var httphedad = _accessor.HttpContext.Request;
// var token = httphedad.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last()
// ?? httphedad.Headers["X-Token"].FirstOrDefault()
// ?? httphedad.Query["Token"].FirstOrDefault()
// ?? httphedad.Cookies["Token"];
// // token校验
// var jwtHandler = new JwtSecurityTokenHandler();
// var userInfo = new UserInfo();
// if (!token.IsNullOrEmpty() && jwtHandler.CanReadToken(token))
// {
// JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token);
// var UserId = jwtToken.Claims.First().Value;
// // userInfo = db.Queryable<SysUser>()
// // .Where(a =>
// // a.Deleted == false && a.Id == user.Id)
// // .Select(a => new UserInfo
// // {
// // UserId = a.Id, UserCode = a.UserCode, UserName = a.NickName,
// // // OrgId = a.OrgId.ToString(), CompanyName = a.CustomerName
// // }).First();
// // var t1 = JsonConvert.DeserializeObject<UserInfo>(temp);
// userInfo = JsonConvert.DeserializeObject<UserInfo>(jwtToken.Claims.First().Value);
// }
// return userInfo;
//}
//public IEnumerable<Claim> GetClaimsIdentity()
//{
// var claims = _accessor.HttpContext.User.Claims.ToList();
// var headers = _accessor.HttpContext.Request.Headers;
// foreach (var header in headers)
// {
// claims.Add(new Claim(header.Key, header.Value));
// }
// return claims;
//}
#endregion 优化前
/// <summary>
/// 保持在请求上下文中的所有声明 不为空
/// </summary>
/// <returns></returns>
12 months ago
public IEnumerable<Claim> GetClaimsIdentity()
{
var claims = new List<Claim>();
var user = _accessor.HttpContext?.User;
if (user != null)
{
claims.AddRange(user.Claims);
}
var headers = _accessor.HttpContext?.Request?.Headers;
if (headers != null)
12 months ago
{
foreach (var header in headers)
{
foreach (var value in header.Value)
{
if (!string.IsNullOrEmpty(value))
{
claims.Add(new Claim(header.Key, value));
}
}
}
12 months ago
}
12 months ago
return claims;
}
#region 键值对获取相应的内容 如果内容不存在则返回默认值 GetClaimValueByType
/// <summary>
/// 键值对获取相应的内容 如果内容不存在则返回默认值
/// </summary>
/// <param name="ClaimType"></param>
/// <returns></returns>
12 months ago
public List<string> GetClaimValueByType(string ClaimType)
{
var claimsIdentity = GetClaimsIdentity();
// if (claimsIdentity == null || !claimsIdentity.Any(item => item.Type == ClaimType))
// {
// return new List<string> { "jti", "TenantId", "CompanyId", "OrgId" }; // 返回包含默认参数的列表
// }
return claimsIdentity.Where(item => item.Type == ClaimType).Select(item => item.Value).ToList();
12 months ago
}
#endregion 键值对获取相应的内容 如果内容不存在则返回默认值 GetClaimValueByType
12 months ago
}