.NET Core - JWT - SecurityTokenNoExpirationException

Viewed 304

In the context of a login page, I try to build a Jwt token in .NET Core.

The middleware is throwing an exception:

SecurityTokenNoExpirationException

Pretty sure everything is into place.

I followed : https://www.youtube.com/watch?edufilter=NULL&ab_channel=IAmTimCorey&v=9QU_y7-VsC8

here is the authentication controller part that creates the 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();

here is the startup.cs part that initializes the JWT middleware:

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

Tell me if you need more info.

Thanks for helping me on this.

1 Answers

The timestamps in a JWT are represented as seconds in UNIX epoch time, not as milliseconds.

RFC7519 defines the numeric date:

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.

Therefore use ToUnixTimeSeconds() instead of ToUnixTimeMilliseconds() when you create the claims.

Related