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 { get { if (_userId == null) { var claimValue = GetClaimValueByType("jti").FirstOrDefault(); _userId = claimValue != null ? claimValue.ObjToString() : "东胜软件"; } return _userId; } set { _userId = value; } } public long GetTenantId() { var token = GetToken(); if (string.IsNullOrEmpty(token)) { return 0; } var jwtHandler = new JwtSecurityTokenHandler(); if (!jwtHandler.CanReadToken(token)) { return 0; } JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token); var tenantIdClaim = jwtToken.Claims.FirstOrDefault(x => x.Type == "TenantId"); return tenantIdClaim != null ? Convert.ToInt64(tenantIdClaim.Value) : 0; } //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); //} public long GetOrgId() { var token = GetToken(); if (string.IsNullOrEmpty(token)) { return 0; } var jwtHandler = new JwtSecurityTokenHandler(); if (!jwtHandler.CanReadToken(token)) { return 0; } JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token); var orgIdClaim = jwtToken.Claims.FirstOrDefault(x => x.Type == "OrgId"); return orgIdClaim != null ? Convert.ToInt64(orgIdClaim.Value) : 0; } //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; //} public string GetCompanyId() { var token = GetToken(); if (string.IsNullOrEmpty(token)) { return string.Empty; } 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 { _tenantId = value; } } // public string CompanyId => GetClaimValueByType("CompanyId").FirstOrDefault().ObjToString(); private string _companyId; public string CompanyId { get { if (_companyId == null) { var companyIdClaim = GetClaimValueByType("CompanyId").FirstOrDefault(); _companyId = companyIdClaim != null ? companyIdClaim.ObjToString() : "东胜软件"; } return _companyId; } set { _companyId = value; } } // public string OrgId => GetClaimValueByType("OrgId").FirstOrDefault().ObjToString(); private string _orgId; public string OrgId { get { if (_orgId == null) { var orgIdClaim = GetClaimValueByType("OrgId").FirstOrDefault(); _orgId = orgIdClaim != null ? orgIdClaim.ObjToString() : "1111111111"; } return _orgId; } set { _orgId = value; } } public UserInfo GetUserInfo() { var user = _accessor.HttpContext?.User; if (user == null || !user.Claims.Any()) { return GetDefaultUserInfo(); } var token = GetToken(); if (string.IsNullOrEmpty(token)) { return GetDefaultUserInfo(); } var jwtHandler = new JwtSecurityTokenHandler(); if (!jwtHandler.CanReadToken(token)) { return GetDefaultUserInfo(); } JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token); var userInfoJson = jwtToken.Claims.First().Value; var userInfo = JsonConvert.DeserializeObject(userInfoJson); return userInfo ?? GetDefaultUserInfo(); } 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() // // .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(temp); // userInfo = JsonConvert.DeserializeObject(jwtToken.Claims.First().Value); // } // return userInfo; //} //public IEnumerable 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 优化前 /// /// 保持在请求上下文中的所有声明 不为空 /// /// public IEnumerable GetClaimsIdentity() { var claims = new List(); var user = _accessor.HttpContext?.User; if (user != null) { claims.AddRange(user.Claims); } var headers = _accessor.HttpContext?.Request?.Headers; if (headers != null) { foreach (var header in headers) { foreach (var value in header.Value) { if (!string.IsNullOrEmpty(value)) { claims.Add(new Claim(header.Key, value)); } } } } return claims; } #region 键值对获取相应的内容 如果内容不存在则返回默认值 GetClaimValueByType /// /// 键值对获取相应的内容 如果内容不存在则返回默认值 /// /// /// public List GetClaimValueByType(string ClaimType) { var claimsIdentity = GetClaimsIdentity(); if (claimsIdentity == null || !claimsIdentity.Any(item => item.Type == ClaimType)) { return new List { "jti", "TenantId", "CompanyId", "OrgId" }; // 返回包含默认参数的列表 } return claimsIdentity.Where(item => item.Type == ClaimType).Select(item => item.Value).ToList(); } #endregion 键值对获取相应的内容 如果内容不存在则返回默认值 GetClaimValueByType }