49 lines
1.7 KiB
C#
49 lines
1.7 KiB
C#
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Security.Claims;
|
|
using System.Text;
|
|
using Kurisu.RemoteCall.Abstractions;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
|
|
namespace Dlhis.Jip.Api.ClientHandlers;
|
|
|
|
public class JipTokenHandler : IAsyncAuthTokenHandler
|
|
{
|
|
/// <inheritdoc />
|
|
public async Task<string> GetTokenAsync(IServiceProvider serviceProvider)
|
|
{
|
|
var configuration = serviceProvider.GetService<IConfiguration>()!;
|
|
|
|
var jwtKey = configuration.GetSection("JinkoOptions:Jip:Key").Value;
|
|
var jwtSecret = configuration.GetSection("JinkoOptions:Jip:Secret").Value;
|
|
const int min = 5;
|
|
|
|
var now = DateTime.Now.AddMinutes(-min);
|
|
var expires = DateTime.Now.AddMinutes(min);
|
|
|
|
var claims = new List<Claim>
|
|
{
|
|
new(JwtRegisteredClaimNames.Nbf, $"{new DateTimeOffset(now).ToUnixTimeSeconds()}"),
|
|
new(JwtRegisteredClaimNames.Exp, $"{new DateTimeOffset(expires).ToUnixTimeSeconds()}"),
|
|
new(JwtRegisteredClaimNames.Iss, jwtKey),
|
|
};
|
|
|
|
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSecret));
|
|
var descriptor = new SecurityTokenDescriptor
|
|
{
|
|
Subject = new ClaimsIdentity(claims),
|
|
Issuer = jwtKey,
|
|
IssuedAt = now,
|
|
NotBefore = now,
|
|
Expires = expires,
|
|
SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
|
|
};
|
|
|
|
var jwtHandler = new JwtSecurityTokenHandler();
|
|
var securityToken = jwtHandler.CreateToken(descriptor);
|
|
var token = await Task.FromResult(jwtHandler.WriteToken(securityToken));
|
|
|
|
return "Bearer " + token;
|
|
}
|
|
} |