首先,需要了解JWT令牌中日期的格式。JWT令牌使用Unix时间戳来表示日期,表示自1970年1月1日00:00:00 UTC以来的秒数。因此,若要创建JWT令牌,需要将日期转换为Unix时间戳格式。
然后,可以使用.NET中的DateTimeOffset和DateTimeOffsetToUnixTimeSeconds方法将日期转换为Unix时间戳格式。示例如下:
DateTimeOffset date = new DateTimeOffset(2022, 1, 1, 0, 0, 0, TimeSpan.Zero);
long unixDate = date.ToUnixTimeSeconds();
DateTimeOffset date = DateTimeOffset.UtcNow.AddMinutes(-5);
long unixDate = date.ToUnixTimeSeconds();
var payload = new JwtPayload
{
{ "sub", "1234567890" },
{ "name", "John Doe" },
{ "iat", unixDate },
{ "exp", unixDate + 3600 }, // 过期时间为1小时后
};
var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("YourSecretKeyHere"));
var credentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: "YourIssuer",
audience: "YourAudience",
claims: payload.Claims,
notBefore: new DateTimeOffset(DateTime.UtcNow).DateTime,
expires: new DateTimeOffset(DateTime.UtcNow.AddDays(1)).DateTime,
signingCredentials: credentials);
var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);