77 lines
2.7 KiB
C#
77 lines
2.7 KiB
C#
using IRaCIS.Core.Domain.Share;
|
|
using Microsoft.Extensions.Options;
|
|
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Security.Claims;
|
|
|
|
namespace IRaCIS.Core.Application.Auth
|
|
{
|
|
|
|
public interface ITokenService
|
|
{
|
|
string GetToken(UserTokenInfo user);
|
|
|
|
bool IsTokenExpired(string token);
|
|
}
|
|
|
|
|
|
public class TokenService : ITokenService
|
|
{
|
|
private readonly JwtSetting _jwtSetting;
|
|
|
|
public TokenService(IOptions<JwtSetting> option)
|
|
{
|
|
_jwtSetting = option.Value;
|
|
}
|
|
|
|
public string GetToken(UserTokenInfo user)
|
|
{
|
|
//创建用户身份标识,可按需要添加更多信息
|
|
var claims = new Claim[]
|
|
{
|
|
new Claim(Microsoft.IdentityModel.JsonWebTokens.JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
|
|
new Claim(JwtIRaCISClaimType.IdentityUserId, user.IdentityUserId.ToString()),
|
|
new Claim(JwtIRaCISClaimType.UserRoleId, user.UserRoleId.ToString()),
|
|
new Claim(JwtIRaCISClaimType.UserName, user.UserName),
|
|
new Claim(JwtIRaCISClaimType.FullName, user.FullName),
|
|
new Claim(JwtIRaCISClaimType.UserTypeId,user.UserTypeId.ToString()),
|
|
new Claim(JwtIRaCISClaimType.UserTypeEnum,user.UserTypeEnum.ToString()),
|
|
new Claim(JwtIRaCISClaimType.UserTypeEnumInt,((int)user.UserTypeEnum).ToString()),
|
|
new Claim(JwtIRaCISClaimType.UserTypeShortName,user.UserTypeShortName),
|
|
new Claim(JwtIRaCISClaimType.PermissionStr,user.PermissionStr),
|
|
new Claim(JwtIRaCISClaimType.IsZhiZhun,user.IsZhiZhun.ToString()),
|
|
new Claim(JwtIRaCISClaimType.IsTestUser,user.IsTestUser.ToString())
|
|
};
|
|
|
|
////创建令牌
|
|
var token = new JwtSecurityToken(
|
|
issuer: _jwtSetting.Issuer,
|
|
audience: _jwtSetting.Audience,
|
|
signingCredentials: _jwtSetting.Credentials,
|
|
claims: claims,
|
|
notBefore: DateTime.Now,
|
|
expires: DateTime.Now.AddMinutes(_jwtSetting.TokenExpireMinute)
|
|
);
|
|
|
|
string jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
|
|
return jwtToken;
|
|
|
|
}
|
|
|
|
public bool IsTokenExpired(string token)
|
|
{
|
|
var handler = new JwtSecurityTokenHandler();
|
|
try
|
|
{
|
|
var jwtToken = handler.ReadJwtToken(token);
|
|
return jwtToken.ValidTo < DateTime.UtcNow;
|
|
}
|
|
catch
|
|
{
|
|
return true; // 无效 Token 也视为已过期
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
}
|