ASP NetCore 8 + JWT with key

282 views Asked by At

Previously I was developing several applications in Asp Net Core 6, one of them is responsible for generating tokens (jwt) that are then used to authenticate against other applications.

The problem arose when creating a new application, but this time in asp net core 8. It is not possible to authenticate it. Any request returns 401.

Token generator:

public TokenDTO GetToken(string id)
{
    var claims = new List<Claim>
    {
        new Claim(JwtRegisteredClaimNames.NameId, id),
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
    };

    var roles = _aplicacionRepository.ObtenerPermisos(id);
    foreach (var rol in roles)
    {
        claims.Add(new Claim(ClaimTypes.Role, rol.Codigo));
    }

    var key = Encoding.ASCII.GetBytes(_settings.Value.Key);

    var token = new JwtSecurityToken(
        issuer: _settings.Value.Issuer,
        audience: _settings.Value.Audience,
        claims: claims.ToArray(),
        expires: DateTime.UtcNow.AddMinutes(_settings.Value.TokenExpirationMinutes),
        signingCredentials: new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha512Signature)
    );

    var tokenHandler = new JwtSecurityTokenHandler();

    return new TokenDTO()
    {
        access_token = tokenHandler.WriteToken(token),
        expires_in = _settings.Value.TokenExpirationMinutes * 60,
        token_type = "bearer"
    };
}

New asp net core 8:

  services.AddAuthentication(def =>
  {
      def.DefaultAuthenticateScheme = Authenticators.Application;
      def.DefaultChallengeScheme = Authenticators.Application;
      def.DefaultScheme = Authenticators.Application;
  })
  .AddJwtBearer(Authenticators.Application, o =>
  {
      o.TokenValidationParameters = new TokenValidationParameters
      {
          ValidIssuer = configuration["Security:Issuer"],
          ValidAudience = configuration["Security:Audience"],
          IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Security:Key"])),
          ValidateIssuer = true,
          ValidateAudience = true,
          ValidateLifetime = true,
          ValidateIssuerSigningKey = true
      };
  })

The error I get in the response is:

Bearer error="invalid_token",error_description="The signature is invalid"

The truth is that I don't know what to try anymore, I can't find documentation about it.

0

There are 0 answers