gpt4 book ai didi

c# - .NET Core - JWT - SecurityTokenNoExpirationException

转载 作者:行者123 更新时间:2023-12-04 08:49:06 28 4
gpt4 key购买 nike

的上下文中登录页面 ,我尝试建立一个 .NET Core 中的 Jwt token .
中间件抛出异常:

SecurityTokenNoExpirationException


很确定一切都到位了。
我关注了: https://www.youtube.com/watch?edufilter=NULL&ab_channel=IAmTimCorey&v=9QU_y7-VsC8
这是创建 JWT 的身份验证 Controller 部分:
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(settings.JwtSecret);
var claims = new Claim[]
{
new Claim(ClaimTypes.Name, user.Email),
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Role, user.RoleId.ToString()),
// token not valid before certain date, in our case, make it valid right away
new Claim(JwtRegisteredClaimNames.Nbf, new DateTimeOffset(DateTime.Now).ToUnixTimeMilliseconds().ToString()),
new Claim(JwtRegisteredClaimNames.Exp, new DateTimeOffset(DateTime.Now.AddMinutes(30)).ToUnixTimeMilliseconds().ToString()),
};

var header = new JwtHeader(
new SigningCredentials(
new SymmetricSecurityKey(key),
SecurityAlgorithms.HmacSha256Signature
)
);

var payload = new JwtPayload(claims);

var securityToken = new JwtSecurityToken(header, payload);
var handler = new JwtSecurityTokenHandler();
这是初始化 JWT 中间件的 startup.cs 部分:
var settings = settingsSection.Get<Settings>();
var key = Encoding.ASCII.GetBytes(settings.JwtSecret);
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
});
如果您需要更多信息,请告诉我。
谢谢你在这方面帮助我。

最佳答案

JWT 中的时间戳在 UNIX epoch time 中表示为秒,而不是毫秒。
RFC7519定义数字日期:

A JSON numeric value representing the number of seconds from 1970-01-01T00:00:00Z UTC until the specified UTC date/time, ignoring leap seconds.


因此使用 ToUnixTimeSeconds()而不是 ToUnixTimeMilliseconds()当您创建声明时。

关于c# - .NET Core - JWT - SecurityTokenNoExpirationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64168351/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com