Home > Blockchain >  JWT token creating throws error 500 when hosted
JWT token creating throws error 500 when hosted

Time:01-04

Im currently writing a webshop in angular asp.net core where I use jwt token authentication. Everything works perfectly until the website is hosted on the internet. After that it throws an internal server error when the server is trying to generate the token. It works perfectly fine when running on localhost or iis.

//program.cs

builder.Services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(x => {

    x.SaveToken = true;
    x.RequireHttpsMetadata = false;
    x.TokenValidationParameters = new TokenValidationParameters {
        ValidateIssuerSigningKey = true,
        ValidateAudience = true,
        ValidateIssuer = true,
        ValidIssuer = builder.Configuration["Jwt:Issuer"],
        ValidAudience = builder.Configuration["Jwt:Issuer"],
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"])),
        ClockSkew = TimeSpan.Zero
    };

});

//this method creates the token in the controller
private string createJwtToken(Users user)
        {
            var jwtTokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.ASCII.GetBytes(_config["Jwt:Key"]);
            var identity = new ClaimsIdentity(new Claim[] {
            new Claim(ClaimTypes.Role, user.Role),
            new Claim(ClaimTypes.Name, $"{user.FirstName} {user.LastName}"),
            new Claim(ClaimTypes.Email, user.Email)

            });
            var credentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = identity,
                SigningCredentials = credentials,
                Expires = DateTime.Now.AddMinutes(20)
            };
            var token = jwtTokenHandler.CreateToken(tokenDescriptor);
            return jwtTokenHandler.WriteToken(token);
        }

I tried changing the issuer and the audience, suspected a no origin allowed error and added cors but nothing helped.

CodePudding user response:

As Krenom answered in the comments

Set ClockSkew to at least 5 min before NOW due to minor differences in time of client/server. The default ClockSkew value is 5 minutes.

ClockSkew = TimeSpan.FromSeconds(300)
  • Related