.NET Core-JWT-SecurityTokenNoExpirationException

Oct 02 2020

로그인 페이지 의 컨텍스트 에서 .NET Core에서 Jwt 토큰 을 빌드하려고합니다 .

미들웨어에서 예외가 발생합니다.

SecurityTokenNoExpirationException

모든 것이 제자리에 있다고 확신합니다.

나는 따랐다 : https://www.youtube.com/watch?edufilter=NULL&ab_channel=IAmTimCorey&v=9QU_y7-VsC8

다음은 JWT를 생성하는 인증 컨트롤러 부분입니다.

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
    };
});

더 많은 정보가 필요하면 알려주세요.

도와 주셔서 감사합니다.

답변

2 jps Oct 02 2020 at 15:38

JWT의 타임 스탬프는 밀리 초가 아닌 UNIX 에포크 시간의 초로 표시됩니다 .

RFC7519 는 숫자 날짜를 정의합니다.

윤초를 무시하고 1970-01-01T00 : 00 : 00Z UTC부터 지정된 UTC 날짜 / 시간까지의 초 수를 나타내는 JSON 숫자 값입니다.

따라서 클레임을 만들 때 ToUnixTimeSeconds()대신 ToUnixTimeMilliseconds()사용하십시오.