:zap:优化功能、类目录

This commit is contained in:
不做码农
2023-08-29 16:56:07 +08:00
parent 94fa69e8ef
commit 07b4b95732
22 changed files with 62 additions and 56 deletions
+2 -1
View File
@@ -1,4 +1,5 @@
using Microsoft.AspNetCore.Hosting;
using Infrastructure.Model;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
-13
View File
@@ -1,13 +0,0 @@
namespace Infrastructure.Constant
{
public class HubsConstant
{
private const string V = "receiveNotice";
public static string ReceiveNotice = V;
public static string OnlineNum = "onlineNum";
public static string MoreNotice = "moreNotice";
public static string OnlineUser = "onlineUser";
public static string LockUser = "lockUser";
public static string ConnId = "connId";
}
}
+4
View File
@@ -2,6 +2,9 @@
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<NoWarn>8632</NoWarn>
</PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
@@ -16,6 +19,7 @@
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="UAParser" Version="3.1.47" />
<PackageReference Include="IPTools.China" Version="1.6.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.7" />
</ItemGroup>
</Project>
+168
View File
@@ -0,0 +1,168 @@
using Infrastructure.Extensions;
using Infrastructure.Model;
using Infrastructure.WebExtensins;
using Microsoft.AspNetCore.Http;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
namespace Infrastructure
{
/// <summary>
/// 2023-8-29已从WebApi移至此
/// </summary>
public class JwtUtil
{
/// <summary>
/// 获取用户身份信息
/// </summary>
/// <param name="httpContext"></param>
/// <returns></returns>
public static TokenModel GetLoginUser(HttpContext httpContext)
{
string token = httpContext.GetToken();
if (!string.IsNullOrEmpty(token))
{
return ValidateJwtToken(ParseToken(token));
}
return null;
}
/// <summary>
/// 生成token
/// </summary>
/// <param name="claims"></param>
/// <returns></returns>
public static string GenerateJwtToken(List<Claim> claims)
{
JwtSettings jwtSettings = new();
AppSettings.Bind("JwtSettings", jwtSettings);
var authTime = DateTime.Now;
var expiresAt = authTime.AddMinutes(jwtSettings.Expire);
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(jwtSettings.SecretKey);
claims.Add(new Claim("Audience", jwtSettings.Audience));
claims.Add(new Claim("Issuer", jwtSettings.Issuer));
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
Issuer = jwtSettings.Issuer,
Audience = jwtSettings.Audience,
IssuedAt = authTime,//token生成时间
Expires = expiresAt,
//NotBefore = authTime,
TokenType = jwtSettings.TokenType,
//对称秘钥,签名证书
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
/// <summary>
/// 验证Token
/// </summary>
/// <returns></returns>
public static TokenValidationParameters ValidParameters()
{
JwtSettings jwtSettings = new();
AppSettings.Bind("JwtSettings", jwtSettings);
if (jwtSettings == null || jwtSettings.SecretKey.IsEmpty())
{
throw new Exception("JwtSettings获取失败");
}
var key = Encoding.ASCII.GetBytes(jwtSettings.SecretKey);
var tokenDescriptor = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
ValidateIssuer = true,
ValidateAudience = true,
ValidIssuer = jwtSettings.Issuer,
ValidAudience = jwtSettings.Audience,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateLifetime = true,//是否验证Token有效期,使用当前时间与Token的Claims中的NotBefore和Expires对比
ClockSkew = TimeSpan.FromSeconds(30)
//RequireExpirationTime = true,//过期时间
};
return tokenDescriptor;
}
/// <summary>
/// 从令牌中获取数据声明
/// </summary>
/// <param name="token">令牌</param>
/// <returns></returns>
public static JwtSecurityToken? ParseToken(string token)
{
var tokenHandler = new JwtSecurityTokenHandler();
var validateParameter = ValidParameters();
token = token.Replace("Bearer ", "");
try
{
tokenHandler.ValidateToken(token, validateParameter, out SecurityToken validatedToken);
return tokenHandler.ReadJwtToken(token);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
// return null if validation fails
return null;
}
}
/// <summary>
/// jwt token校验
/// </summary>
/// <param name="jwtSecurityToken"></param>
/// <returns></returns>
public static TokenModel? ValidateJwtToken(JwtSecurityToken jwtSecurityToken)
{
try
{
if (jwtSecurityToken == null) return null;
IEnumerable<Claim> claims = jwtSecurityToken?.Claims;
TokenModel loginUser = null;
var userData = claims.FirstOrDefault(x => x.Type == ClaimTypes.UserData)?.Value;
if (userData != null)
{
loginUser = JsonConvert.DeserializeObject<TokenModel>(userData);
loginUser.ExpireTime = jwtSecurityToken.ValidTo;
}
return loginUser;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return null;
}
}
/// <summary>
///组装Claims
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
public static List<Claim> AddClaims(TokenModel user)
{
var claims = new List<Claim>()
{
new Claim(ClaimTypes.PrimarySid, user.UserId.ToString()),
new Claim(ClaimTypes.Name, user.UserName),
new Claim(ClaimTypes.UserData, JsonConvert.SerializeObject(user))
};
return claims;
}
}
}
@@ -1,6 +1,6 @@
using System.Collections.Generic;
namespace Infrastructure
namespace Infrastructure.Model
{
/// <summary>
/// 获取配置文件POCO实体类
@@ -80,6 +80,14 @@ namespace Infrastructure
/// token时间(分)
/// </summary>
public int Expire { get; set; } = 1440;
/// <summary>
/// 刷新token时长
/// </summary>
public int RefreshTokenTime { get; set; }
/// <summary>
/// token类型
/// </summary>
public string TokenType { get; set; } = "Bearer";
}
public class Gen
+48
View File
@@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace Infrastructure.Model
{
public class TokenModel
{
public long UserId { get; set; }
public long DeptId { get; set; }
public string UserName { get; set; }
/// <summary>
/// 角色集合
/// </summary>
public List<string> RoleIds { get; set; }
/// <summary>
/// 角色集合(数据权限过滤使用)
/// </summary>
public List<Roles> Roles { get; set; }
/// <summary>
/// Jwt过期时间
/// </summary>
public DateTime ExpireTime { get; set; }
/// <summary>
/// 权限集合
/// </summary>
//public List<string> Permissions { get; set; } = new List<string>();
public TokenModel()
{
}
public TokenModel(TokenModel info, List<Roles> roles)
{
UserId = info.UserId;
UserName = info.UserName;
DeptId = info.DeptId;
Roles = roles;
RoleIds = roles.Select(f => f.RoleKey).ToList();
}
}
public class Roles
{
public long RoleId { get; set; }
public string RoleKey { get; set; }
public int DataScope { get; set; }
}
}