AssetManager.API/AssetManager.Services/Services/JwtService.cs
niannian zheng d39a6347cd feat: 实现微信登录和用户信息管理功能
- 添加微信登录功能,支持通过微信小程序登录
- 实现用户信息管理接口,包括获取用户信息和统计数据
- 新增投资组合列表和总资产统计接口
- 完善JWT令牌生成逻辑,支持可选用户名
- 添加数据库初始化配置和连接字符串
- 移除传统登录和注册功能,专注微信登录方案
2026-02-26 11:56:14 +08:00

49 lines
1.6 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
namespace AssetManager.Services.Services;
public class JwtService
{
private readonly string _secretKey;
private readonly string _issuer;
private readonly string _audience;
public JwtService(IConfiguration configuration)
{
_secretKey = configuration["Jwt:SecretKey"] ?? "your-strong-secret-key-here-2026";
_issuer = configuration["Jwt:Issuer"] ?? "AssetManager";
_audience = configuration["Jwt:Audience"] ?? "AssetManager";
}
public string GenerateToken(string userId, string userName, string email)
{
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.Sub, userId ?? ""),
new Claim(JwtRegisteredClaimNames.Email, email ?? ""),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
// 如果userName不为null添加到claims中
if (!string.IsNullOrEmpty(userName))
{
claims.Add(new Claim(JwtRegisteredClaimNames.Name, userName));
}
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_secretKey));
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: _issuer,
audience: _audience,
claims: claims,
expires: DateTime.Now.AddHours(24),
signingCredentials: credentials);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}